如何根据背景图像的高度和宽度设置 DIV 尺寸
How to set DIV dimensions as per the height and width of background-image
我有一个带有背景图像的DIV。但我的要求是如何根据背景图像的高度和宽度扩展 DIV 大小。我在此链接的帮助下尝试了一些代码。
var src = $('#divID').css('background-image').
replace('url', '')
.replace('(', '')
.replace(')', '')
.replace('"', '')
.replace('"', '');
$('body').append('<img id="appendedImg" src="' + src + '" style="height:0px;width:0px"');
var img = document.getElementById('appendedImg');
var width = img.clientWidth;
var height = img.clientHeight;
$('#appendedImg').detach();
如果可能的话,我只是在寻找任何优雅的解决方案。
您可能只需要在加载时查找宽度/高度:
var img = document.getElementById('appendedImg');
img.onload = function() {
var width = img.width;
var height = img.height;
console.log(width,height);
};
另外,您不需要附加它,创建新图像应该就足够了。以下是我会怎么做:
var $div = $('#divID'),
src = $div.css('background-image').replace(/url'('"([^'"]+).*/,'$1');
$(new Image).load(function() {
$div.width(this.width).height(this.height);
}).attr('src', src);
我会先加载img,然后获取其高度和宽度:
imgSrc = 'http://ajthomas.co.uk/wp-content/themes/ajthomascouk/library/images/logo.png'
// append the temp imag
$('body').append('<img src="'+imgSrc+'" alt="" style="display:none" id="dummyImage"/>');
// get the image width and height
imgWidth = $('#dummyImage').width()+'px';
imgHeight = $('#dummyImage').height()+'px';
// remove the image
$('#dummyImage').remove();
// set the css for the div
$('#imADiv').css({height: imgHeight, width: imgWidth, 'background-image': 'url('+imgSrc+')'});
在这里为您编码 - http://jsfiddle.net/LTdtM/
相关文章:
- 内容可编辑DIV单击/插入符号设置
- 使用Javascript对象为具有两个背景图像的DIV设置样式时出现问题
- Javascript/jQuery在可编辑的DIV中设置光标
- 如何设置DIV背景图像css jquery
- JS - 使用变量设置 Div 背景颜色
- 如何使用 JavaScript 动态设置 DIV 元素的左侧和顶部 CSS 位置
- 如何根据背景图像的高度和宽度设置 DIV 尺寸
- 如何滚动以在屏幕底部设置 DIV 的底部(监视器)
- 根据表变量宽度设置 DIV 的宽度
- 如何设置DIV或LI“;类“;按星期几
- 聚合物-设置DIV
- 设置DIV高度,使文本不被水平剪切或切片
- 设置DIV的大小,而不必等待页面加载结束
- 设置DIV的高度以对应该DIV内锚点的位置
- 使用javascript和css设置DIV的滚动高度
- 使用非法字符设置DIV ID名称
- 在另一个内容上设置Div位置
- 在文档准备好之前设置Div值
- 在Dojo中设置DIV或SPAN宽度的动画
- 如何使用角度响应数据设置DIV的背景图像