使用 jQuery 从背景图像获取尺寸

发布于 2024-09-11 07:22:16 字数 627 浏览 0 评论 0原文

我正在将背景图像加载到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

黑色毁心梦 2024-09-18 07:22:16
​$('<img src='images/menu-"+name+"-h.png' />')​.attr('src',function(){
    return $('body').css('background-image');
})​​​.load(function(){
    w = $(this).width();
    h = $(this).height();
})​;

这会等到图像加载后获取高度和宽度。

​$('<img src='images/menu-"+name+"-h.png' />')​.attr('src',function(){
    return $('body').css('background-image');
})​​​.load(function(){
    w = $(this).width();
    h = $(this).height();
})​;

This waits till the image is loaded to grab the height and width.

沐歌 2024-09-18 07:22:16
var img=new Image();
img.onload=function(){
    alert(img.width);
    alert(img.height);
};
img.src="image.png";
var img=new Image();
img.onload=function(){
    alert(img.width);
    alert(img.height);
};
img.src="image.png";
对岸观火 2024-09-18 07:22:16

Jquery

w = $("img").width();
h = $("img").height();

Ruby

IO.read('image.png')[0x10..0x18].unpack('NN')

这会生成一个数组 [width,height],您可以提取 [0] 作为宽度等...

Jquery

w = $("img").width();
h = $("img").height();

Ruby

IO.read('image.png')[0x10..0x18].unpack('NN')

This yields an array [width,height] which you can extract a[0] for width etc...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文