获取 img 的宽度和高度,并使用 javascript 将其添加到最近的父级
我已经弄清楚如何使用 javascript 获取图像的宽度和高度。我的问题是如何将宽度和高度应用到它最近的父级,在这种情况下它是使用 javascript 的 li。
<ul>
<li> <img src="img1.jpg" /> </li>
<li> <img src="img2.jpg" /> </li>
</ul>
我正在使用的js:
$(window).load(function() {
var pic = $('img');
var w = pic.width();
var h = pic.height();
pic.removeAttr("width");
pic.removeAttr("height");
$('ul li').css('width',w);
});
现在它只是获取第一个图像的宽度和高度并将其应用到每个li。
I've figured out how to get the width and hight of an image using javascript. My question is how do I apply the width and height to it's nearest parent in this case it's li using javascript.
<ul>
<li> <img src="img1.jpg" /> </li>
<li> <img src="img2.jpg" /> </li>
</ul>
The js i'm using:
$(window).load(function() {
var pic = $('img');
var w = pic.width();
var h = pic.height();
pic.removeAttr("width");
pic.removeAttr("height");
$('ul li').css('width',w);
});
Right now it is only getting the width and height of the first image and applying it to every li.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
下面的解决方案已被修改以证明其有效性:
CSS:
HTML:
jQuery:
示例: http://jsfiddle.net/kfnhh /
只需删除点击事件处理程序,代码就可以在您的环境中轻松实现。
The solution below has been modified to demonstrate its effectiveness:
CSS:
HTML:
jQuery:
Example: http://jsfiddle.net/kfnhh/
Simply remove the click event handler and the code should be easily implemented in your environment.
尝试类似的事情:
没有尝试,但想法就在那里。
Try something like :
Didn't try but the idea is there.
另一种方法:
Another way to it:
.parent() 将为您提供您正在使用它的控件的父级。在您的情况下,以下内容应该为您提供图像控件的父控件。
.parent() will get you the parent of what ever control you are using it on. In your case the following should get you the parent control of your image control.
尽可能少地改变:
这有效吗?
To change as little as possible:
Would that work?