javascript 使用css设置背景的宽度和高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11667469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setting width and height for background using css
提问by Fahim Parkar
I want to set background width and height of the image.
我想设置图像的背景宽度和高度。
document.getElementById('outerModalPopupDiv').style.backgroundImage = "url('samandar_003.jpeg')";
document.getElementById('outerModalPopupDiv').style.backgroundRepeat = "no-repeat";
Now I want to set Image width and height. I know background-size: 200px 50px;
set height and width, however I can't use the same. I have to set the width and height in above format.
现在我想设置图像的宽度和高度。我知道background-size: 200px 50px;
设置高度和宽度,但是我不能使用相同的。我必须以上述格式设置宽度和高度。
If I use
如果我使用
document.getElementById('outerModalPopupDiv').style.background.size = "200px 500px";
it won't work. Image remain same as it is.
它不会工作。图像保持不变。
Any idea how can I make this working.
任何想法我怎样才能使它工作。
回答by scumah
回答by r3bel
with css3 you can set the Background-size:
使用 css3,您可以设置背景大小:
#outerModalPopupDiv {
background-size: 200px 500px;
}
as you can see here
正如你在这里看到的
alternatively if you want to set it with javascript you can create a css class and add the class to an element
或者,如果你想用 javascript 设置它,你可以创建一个 css 类并将该类添加到一个元素
javascript:
javascript:
document.getElementById("outerModalPopupDiv").className += "resizeBg200x500";
css:
css:
.resizeBg200x500 {
background-size: 200px 500px;
}
or directly with javascript:
或直接使用 javascript:
document.getElementById("outerModalPopupDiv").style.backgroundSize="200px 500px";
or another alternative with jQuery :)
或 jQuery 的另一种选择:)
$("#outerModalPopupDiv").css("background-size","200px 500px");
background-size is css3, but widely supported by many browsers as you can see here
background-size 是 css3,但正如你在这里看到的,它被许多浏览器广泛支持
回答by SpaceBeers
Personally I'd make a class with the re sizing in and the add that dynamically using JS
就我个人而言,我会制作一个调整大小并使用 JS 动态添加的类
http://jsfiddle.net/spacebeers/FFeEh/15/
http://jsfiddle.net/spacebeers/FFeEh/15/
document.getElementById('outerModalPopupDiv').style.backgroundRepeat = "no-repeat";
var element = document.getElementById('outerModalPopupDiv');
element.className += element.className ? ' backgroundResize' : 'backgroundResize';?