一個JavaScript操作元素定位元素的實例
更新時間:2014年10月29日 16:48:14 投稿:whsnow
操作元素定位元素,大家會想到使用js來實現(xiàn),下面有個不錯的示例,大家可以看看
操作元素定位元素,用js來實現(xiàn)是個不錯的選擇,下面有個示例,需要的朋友可以看看
<!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獲取元素尺寸和大小操作總結(jié)
- javascript數(shù)組操作(創(chuàng)建、元素刪除、數(shù)組的拷貝)
- js/jQuery對象互轉(zhuǎn)(快速操作dom元素)
- JS實現(xiàn)為動態(tài)創(chuàng)建的元素添加事件操作示例
- JS實現(xiàn)數(shù)組簡單去重及數(shù)組根據(jù)對象中的元素去重操作示例
- js中數(shù)組插入、刪除元素操作的方法
- JavaScript DOM元素常見操作詳解【添加、刪除、修改等】
- JavaScript中用sort()方法對數(shù)組元素進行排序的操作
- js有關(guān)元素內(nèi)容操作小結(jié)
- JavaScript操作元素實例大全
相關(guān)文章
本地Bootstrap文件字體圖標引入?yún)s無法顯示問題的解決方法
這篇文章主要為大家詳細介紹了本地Bootstrap文件字體圖標引入?yún)s無法顯示問題的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12