一個JavaScript操作元素定位元素的執行個體,javascript執行個體

來源:互聯網
上載者:User

一個JavaScript操作元素定位元素的執行個體,javascript執行個體

操作元素定位元素,用js來實現是個不錯的選擇,下面有個樣本,需要的朋友可以看看

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>每天一個JavaScript執行個體-操作元素定位元素</title> <style> div#a{ width:500px; } div{ border:1px solid #000; padding:10px; } #cursor{ position:absolute; background-color:#ff0; width:20px; height:20px; left:50px; top:300px; } </style> <script> function positionObject(obj){ var rect = obj.getBoundingClientRect(); return [rect.left,rect.top]; } window.onload = function(){ var tst = document.documentElement.getBoundingClientRect(); alert(tst.top); var cont = 'A'; var cursor = document.getElementById("cursor"); while(cont){ cont = prompt("where do you want to move the cursor block?","A"); if(cont){ cont = cont.toLowerCase(); if(cont == "a"||cont=="b"||cont=="c"){ var elem = document.getElementById(cont); var pos = positionObject(elem); console.log(pos); cursor.setAttribute("style","top:"+pos[1]+"px;"+"left:"+pos[0]+"px"); } } } } </script> </head> <body> <div id = "a"> <p>A</p> <div id ="b"> <p>B</p> <div id="c"> <p>C</p> </div> </div> </div> <div id="cursor"> </div> </body> </html>

關於 javascript 中的定位元素的問題

補充:lz你還是加我一下百度hi或者qq25846111,我們具體來討論一下

請問"[html][body][table][tbody]"是不是指
<html>
<body>
<table>
<tbody>這樣的形式?

如此的話,可以一級一級進行尋找
// 獲得所有的body元素列表(在這裡將只有一個)
myDocumentElements=document.getElementsByTagName("body");
// 我們所需要body元素是這個列表的第一個元素
myBody=myDocumentElements.item(0);
// 現在,讓我們獲得body的子項目中所有的table元素
myPElements=myBody.getElementsByTagName("table");
//在這裡如果需要尋找指定的table可以用迴圈語句從item中尋找,我假設取第一個
myTable=myPElements.item(0);
//下面是重複上面的過程獲得tbody
myTbody=myTable..getElementsByTagName("tbody").item(0);

當然還有其他方法,lz可以看一下這個連結
developer.mozilla.org/...86HTML

關於dom編程有問題歡迎發訊息
 
JavaScript中怎通過一個元素去尋找該元素的子項目節點

function get_nextSibling(n)
{
y=n.nextSibling;
while (y.nodeType != 1)
{
y=y.nextSibling;
}
return y;
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.