使用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.
更多推荐
发布评论