使用jQuery从background

编程入门 行业动态 更新时间:2024-10-24 20:13:36
使用jQuery从background-image获取维度(Getting dimensions from background-image using 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' />"); });

};

最满意答案

​$('<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.

更多推荐

本文发布于:2023-07-06 07:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047325.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:jQuery   background

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!