[英]Why am I getting the error: Uncaught TypeError: Cannot read property 'left' of undefined
HTML: HTML:
<div id="opening_0" style="background-color: #bfbfbf; position: absolute; left: 45px; top: 45px; height: 202.5px; width: 157.5px; overflow: hidden; z-index: 4;" ondrop="drop(event, this)" ondragover="allowDrop(event)" onclick="photos_add_selected_fid(this);"> </div>
Javascript: 使用Javascript:
canvas.style.left = $("#opening_0").style.left - img.width + "px";
canvas.style.top = $("#opening_0").style.top - img.height + "px";
Why am I getting this error"? 为什么会出现此错误”?
使用jQuery的.css()函数,因为这基本上就是您使用jQuery的原因:
canvas.style.left = parseInt($("#opening_0").css('left')) - img.width + "px";
The error is because $("#opening_0")
returns a jQuery object which wraps the matched DOM nodes. 该错误是因为
$("#opening_0")
返回包装了匹配的DOM节点的jQuery对象。 To get to the underlying DOM nodes, you can treat it like an array: $("#opening_0")[0]
will work, for example. 要访问底层的DOM节点,可以将其视为数组:例如,
$("#opening_0")[0]
将起作用。
But , this approach won't work well, since style.left
will return a string which could have px or percentage values. 但是 ,此方法效果不好,因为
style.left
将返回可能具有px或百分比值的字符串。 You could use $("#opening_0").offset().left
instead which will always return a numerical value. 您可以使用
$("#opening_0").offset().left
代替,它将始终返回数字值。
jQuery objects do not have a style
property. jQuery对象没有
style
属性。
If you want to have access to it, either use the vanilla javascript way: 如果您想访问它,请使用香草javascript方法:
document.getElementById("opening_0").style.left;
...or "unwrap" the jQuery object like so: ...或“解开” jQuery对象,如下所示:
$("#opening_0")[0].style.left;
I'd recommend using the first method. 我建议使用第一种方法。 Just remember to parse the value by using
parseInt()
. 只需记住使用
parseInt()
解析值即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.