<html>
<head>
<style>
#wrapper{
position: absolute;
top : 250px;
width: 500px;
height: 500px;
border: 1px solid red;
}
.tagging{
position: absolute;
border: 1px solid black;
width : 20px;
height: 30px;
}
</style>
<script>
window.onload = function(event){
var wrapper = document.getElementById("wrapper");
var wrapperOffsetTop = wrapper.offsetTop;
wrapper.onmousedown = function(event){
var div = document.createElement("div");
div.className = "tagging";
div.style.top = event.clientY - wrapperOffsetTop;
wrapper.appendChild(div);
}
}
</script>
</head>
<body>
<div id="wrapper">
</div>
</body>
</html>
这是我的代码。我希望做一个用户可以点击该区域的应用程序,它将附加一个带有鼠标光标位置的div框,但它似乎不起作用。为什么?
在我添加+"px"
但为什么在我的实际应用中它不起作用:
<html>
<head>
<style>
.tagging{
border: 1px solid red;
position: absolute;
padding: 0px;
margin: 0px;
width : 20px;
height: 20px;
}
</style>
<script>
window.onload = function(){
//get Information about imgWrapper
var imgWrapper = document.getElementById("imgwrapper");
var wrapperOffsetTop = imgWrapper.offsetTop;
var wrapperOffsetLeft = imgWrapper.offsetLeft;
//set the image wrapper to be the same size as the image
var img = document.getElementsByTagName('img');
imgWrapper.style.width = img[0].width;
//when image wrapper is click, append div element
img[0].onmousedown = function(event) {
event.preventDefault();
//create tag with class
var div = document.createElement("div");
div.className = "tagging";
imgwrapper.appendChild(div);
//get the position of mouse cursor
var mouseX = event.clientX;
var mouseY = event.clientY;
//set the position of the div
div.style.top = (mouseY - wrapperOffsetTop) + "px";
div.style.left = (mouseX - wrapperOffsetLeft) + "px";
//mousemove event
//assign mouse move action on image
//mouse up
}
}
</script>
</head>
<body>
<div id="imgwrapper">
<img src="jlin.jpg">
</div>
<form action="./yipee.php" method="POST" id="noob">
<input type="submit">
</form>
</body>
</html>
答案 0 :(得分:5)
您要将top属性设置为 Number 。它需要一个CSS长度,这需要单位。
div.style.top = (event.clientY - wrapperOffsetTop) + "px";
答案 1 :(得分:2)
更新:初始代码适用于Firefox和Chrome。要使它在IE8中工作,它不支持W3 DOM事件对象,您需要选择window.event if(!event){ event = window.event; }
除非我误解了你的问题,否则它应该只是为左边距的偏移添加偏移:
<html>
<head>
<style>
#wrapper{
position: absolute;
top : 250px;
width: 500px;
height: 500px;
border: 1px solid red;
}
.tagging{
position: absolute;
border: 1px solid black;
width : 20px;
height: 30px;
}
</style>
<script>
window.onload = function(event){
var wrapper = document.getElementById("wrapper");
var wrapperOffsetTop = wrapper.offsetTop;
var wrapperOffsetLeft = wrapper.offsetLeft;
wrapper.onmousedown = function(event){
if (!event) {
event = window.event;
}
var div = document.createElement("div");
div.className = "tagging";
div.style.top = event.clientY - wrapperOffsetTop;
div.style.left = event.clientX - wrapperOffsetLeft;
wrapper.appendChild(div);
}
}
</script>
</head>
<body>
<div id="wrapper">
</div>
</body>
</html>