使用 jQuery 从背景图像获取尺寸
我正在将背景图像加载到 div 中。是否可以从该图像中获取尺寸?
我正在尝试创建一个函数,可以动态用图像替换文本,以便在菜单中使用。
$.fn.MenuImages = function() {
return this.each(function(i) {
var name = $(this).find('a').attr('title');
$(this).css("background-image","url(images/menu-"+name+"-h.png)");
});
};
问题是图像的大小并不相同。我不知道如何读取文件的尺寸,除非我将它加载到隐藏的 div 或其他东西中,但这听起来很脏。有什么建议吗?谢谢!
固定的:
$.fn.MenuImages = function() {
return this.each(function(i) {
var link = $(this).find('a');
var name = link.attr('title');
link.html("<img src='images/menu-"+name+"-h.png' />");
});
};
I'm loading a background image into a div. Is it possible to get the dimensions from this image?
I'm trying to make a function that will replace text with images on the fly, for use in the menu.
$.fn.MenuImages = function() {
return this.each(function(i) {
var name = $(this).find('a').attr('title');
$(this).css("background-image","url(images/menu-"+name+"-h.png)");
});
};
Problem is that the images do not all have the same size. I'm not sure how to read the file's dimensions unless i load it in a hidden div or something, but that sounds so dirty. Any recommendations? Thanks!
Fixed:
$.fn.MenuImages = function() {
return this.each(function(i) {
var link = $(this).find('a');
var name = link.attr('title');
link.html("<img src='images/menu-"+name+"-h.png' />");
});
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这会等到图像加载后获取高度和宽度。
This waits till the image is loaded to grab the height and width.
Jquery
Ruby
这会生成一个数组 [width,height],您可以提取 [0] 作为宽度等...
Jquery
Ruby
This yields an array [width,height] which you can extract a[0] for width etc...