放在哪个地方都可以,就是绝对定位了。用CSS属性position: absolute配合top和left两个属性(确定左上角坐标)来实现。但需注意,这个绝对是相对于上级元素来说的,要相对于整个页面随处可放,就要把它作为<html>的子元素。
我有一个用鼠标位置定位元素的html发给你参考一下:
<!doctype html><html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{
margin: 0
padding: 0
}
#container{
position: relative
background: #eeeeff
width: 800px
height: 600px
border: 1px solid red
margin: 20px auto
}
#moveBox{
position: absolute
width: 100px
height: 100px
top: 150px
left: 250px
background: #ddffdd
line-height: 100px
color: red
border: 1px solid black
}
</style>
<script>
function move(){
var box=document.getElementById("moveBox")
var container=document.getElementById("container")
var containerX=container.offsetLeft
var containerY=container.offsetTop
var thisScrollTop = document.documentElement.scrollTop + document.body.scrollTop
var thisScrollLeft = document.documentElement.scrollLeft + document.body.scrollLeft
var posX=event.clientX+thisScrollLeft-containerX
var posY=event.clientY+thisScrollTop-containerY
console.log("posX="+posX+",posY="+posY)
box.style.top=posY+"px"
box.style.left=posX+"px"
//console.log("x="+event.clientX+",y="+event.clientY)
}
</script>
</head>
<body>
<div id="container" onmousemove="move()">
<div id="moveBox">
用鼠标移动我
</div>
</div>
</body>
</html>
<script>function keydown(e){
switch(e){
case 38: document.getElementById('name').style.top=parseInt(document.getElementById('name').style.top)-5+"px"
break
case 40: document.getElementById('name').style.top=parseInt(document.getElementById('name').style.top)+5+"px"
break
}
}
document.onkeydown =keydown//按上下键
</script>
这里你需要注意的是,首先要把div的top给写好,也就是说你要把他写成position:absolute或者position:related
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)