一个JavaScript操作元素定位元素的实例
作者:bea
操作元素定位元素,用js来实现是个不错的选择,下面有个示例,需要的朋友可以看看 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>每天一个JavaScript实例-操作元素定位元素</title> <style> div#a{
操作元素定位元素,用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>
有用 | 无用
<!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>
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- js读取cookie方法总结
- jQuery获取对象简单实现方法小结
- js 通过cookie实现刷新不变化树形菜单
- 判断字符串的长度(优化版)中文占两个字符
- javascript根据时间生成m位随机数最大13位
- D3.js 从P元素的创建开始(显示可加载数据)
- jquery 获取 outerHtml 包含当前节点本身的代码
- 如何调试异步加载页面里包含的js文件
- fckeditor粘贴Word时弹出窗口取消的方法
- js中style.display=""无效的解决方法
- Js实现网页键盘控制翻页的方法
- javascript实现iframe框架延时加载的方法
- js中iframe调用父页面的方法
- js防止页面被iframe调用的方法
- escape函数解决js中ajax传递中文出现乱码问题
- js防止DIV布局滚动时闪动的解决方法
- js实现window.open不被拦截的解决方法汇总
- 一个JavaScript获取元素当前高度的实例
- JS 实现列表与多选框选择附预览动画