javascript常用函数使用

来源:互联网 发布:创业公司取名 知乎 编辑:程序博客网 时间:2024/06/04 08:11

scrollIntoView() 返回顶段

ScrollIntoView()用法:先选中一个dom元素<temp>,可以利用getElementById(),getElementByTagName()等函数获取。调用temp.ScrollIntoView();如果<temp>元素不在窗口内就会自动滚动直到<temp>所在位置。
因此返回顶端只需要回到<body>所在位置就可以了

function top(){var temp=document.getElementsByTagName("body");temp[0].scrollIntoView();}

childNodes/children获取子节点

<html><head><meta charset="utf-8"/><title>获取子节点</title><script>function child(){var temp=document.getElementById("ul");//获取父节点<ul>var objchild=temp.childNodes;//获取子节点数组var strTags="";for(var i=0;i<objchild.length;i++){    eletag=objchild[i];    strTags+=eletag.nodeName+"\n";}alert(strTags);}</script></head><body><ul id="ul">  <li onclick="child1()">苹果</li>  <li>香蕉</li>  <li>西瓜</li></ul></body></html>

集合对象

  1. document.anchors 包含html网页中所有带name的<a>标签(ps:HTML5不支持name属性);
  2. document.forms 包含HTML网页中所有<form>标签
  3. document.images 包含所有<img>标签
  4. document.links 包含所有<a>标签

    javascript设置属性

  5. getAttribute(temp) 获取temp属性的值

  6. setAttribute(temp,value) 设置属性temp值为value
  7. removeAttribute(temp)删除temp属性
<html><head><meta charset="utf-8" /><title>设置属性</title><script>function move(direct){var tag=document.getElementById("p");//获取id="p"的元素tag.setAttribute("align",direct);//设置id="p"元素的属性align值为函数参数direct}</script></head><body id="body"><p align="left" id="p">你好时间</p><input type="button" onclick="move('left')" value="向左"/><input type="button" onclick="move('center')" value="中间"/><input type="button" onclick="move('right')" value="向右"/></body></html>

新建和插入节点

javascript事件属性

使用event对象来调用
1. type获取事件类型
2. target获取事件目标
3. stopPropagation()阻止事件
4. preventDefault()阻止事件默认行为

<script>var obj =document.getElementById("btn");obj.addEventListener("click",show);function show(event){ alert(event.type);//显示事件属性为:click}</script>
0 0