移动使用 Jquery 创建的 div
我真正想要的是能够单击新创建的 div,然后单击屏幕上的其他位置并将 div 移动到那里。
我的代码:
$(function() {
$('a#linkA').click(function() {
$('#container')
.prepend("<div id='cloneA' onclick='moveA();'> <img src='A.gif' alt='A' </div>")
});
});
function moveA(event) {
var posx = event.pageX; //get the mouse's x coord
var posy = event.pageY; //get the mouse's y coord
document.getElementById("cloneA").style.left = posx;
document.getElementById("cloneA").style.top = posy;
当我在 firefox 中运行它并使用 firebug 时,它显示“document.getElementByID("cloneA").style.left 未定义...为什么会这样,我该怎么做才能让它执行我的操作想? 谢谢!
What I really want is to be able to click on the newly created div then click somewhere else on the screen and have the div move there.
My code:
$(function() {
$('a#linkA').click(function() {
$('#container')
.prepend("<div id='cloneA' onclick='moveA();'> <img src='A.gif' alt='A' </div>")
});
});
function moveA(event) {
var posx = event.pageX; //get the mouse's x coord
var posy = event.pageY; //get the mouse's y coord
document.getElementById("cloneA").style.left = posx;
document.getElementById("cloneA").style.top = posy;
When I run this in firefox and use firebug, it says "document.getElementByID("cloneA").style.left isn't defined...Why is that and what can I do to get this to do what I want?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你有几个不同的问题。第一,您没有将事件传递给
moveA(event)
。另外,当你设置left
和top
时,你需要为你设置的left
和top的值添加一种维度
到 (px
,%
)。并且,要设置left
和top
,您需要一个position:absolute
或一个position:relative
来使#moveA
移动到该位置。此外,如果您要添加多个
#moveA img
,则应该向这些元素的ID
属性附加一个唯一的编号。http://jsfiddle.net/WkkCE/
You've got a couple of different issues. One, you're not passing an event to
moveA(event)
. Also, when you set theleft
andtop
, you need to add a type of dimension to the value you setleft
andtop
to (px
,%
). And, to set theleft
andtop
, you need aposition: absolute
or aposition: relative
to make the#moveA
move to that position.Additionally, if you're going to add multiple
#moveA img
's, you should really append a unique number to those element'sID
attribute.http://jsfiddle.net/WkkCE/