H5的DOM操作(native)

(1)改变内容,改变css,改变事件。注意:css中的background-color对应着dom操作中的backgroundColor,dom中都是驼峰命名法。
          var p = document.getElementId('p-id');
          p.innerHTML = 'abc';
          p.innerText = 'dog';
 
          p.style.color = '#ff0000';
          p.style.fontSize = '20px';
          p.style.paddingTop = '2em';
 
          p.onclick = function(){alert("ok");}
(2)创建一个节点,插入
      var parent = document.getElementById('parent');
      var childNew = document.createElement('p');
      childNew .id = "childNew ";
      childNew .innerText = "childNew ";
      parent.appendChild(childNew );//插到最末
      
      var existingElement = document.getElementById('existingItem');
      parent.insertBefore(childNew,existingElement);
(2.5)获取属性
      var a = document.getElementById('myid');
      var attr = a.getAttribute('src');//获取a元素的src属性。
      a.setAttribute("src","mynulll");//设置src属性。
      更简单的做法是:a.src,不需要在使用set get这么麻烦的函数了。
(3)删除节点
      var self = document.getElementById('to-be-removed');
      var parent = self.parentElement;
      var removed = parent.removeChild(self);
      removed == self;//true
 
(4)提交form验证做法
注意要return true来告诉浏览器继续提交,如果return false,浏览器将不会继续提交form,这种情况通常对应用户输入有误,提示用户错误信息后终止提交form。
<form id="test-form" action="http://www.xxx.com/a.php" onsubmit="return checkForm()">
    <input type="text" name="test">
    <button type="submit">Submit</button>
</form>
 
<script>
function checkForm() {
    var form = document.getElementById('test-form');
    // 可以在此修改form的input...
    // 继续下一步:
    return true; //继续提交到后端脚本
       // return false;//如果false,就不提交到脚本
}
</script>
 
(5)元素、窗体偏移等。
获取一个元素相对于浏览器窗体的偏移,一般用于下拉后一些需要置顶的元素。document.getElementById("id3").getBoundingClientRect()
posted @ 2018-04-04 16:02  东方春  阅读(846)  评论(0编辑  收藏  举报