Html 在javascript中更改背景图像大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15755992/
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
Change background-image size in javascript
提问by pinkie
I have been attempting to put a repeating background image on a website, with the basic CSS
我一直在尝试使用基本的 CSS 在网站上放置一个重复的背景图像
background-image: url('url_here');
background-attachment: fixed;
background-repeat: repeat;
however, id like to be able to change the size of the image im using on refresh, using javascript. CSS has the function
但是,id 希望能够在刷新时使用 javascript 更改图像的大小。CSS有这个功能
background-size: 300px;
but unfortunately the COM style object doesnt - see herefor what it can do for backgrounds. This leaves me with one option: using an HTML image that repeats itself, that i can then edit with the COM style object.
但不幸的是,COM 样式对象没有 - 请参阅此处了解它对背景的作用。这给我留下了一个选择:使用重复的 HTML 图像,然后我可以使用 COM 样式对象进行编辑。
So, boiled down, my question is: is there a way to repeat an HTML image that is NOT a background image? Any help is greatly appreciatted.
所以,归根结底,我的问题是:有没有办法重复不是背景图像的 HTML 图像?任何帮助都非常感谢。
回答by Rodney Golpe
Actually, you CAN affect the background size in javascript like so:
实际上,您可以像这样影响 javascript 中的背景大小:
document.getElementById("el_id").style.backgroundSize = "100px 100px";
Check out this fiddle: http://jsfiddle.net/Lph2W/. The CSS sets the background image size to 200px X 200px, then the JS updates it to 100px X 100px.
看看这个小提琴:http: //jsfiddle.net/Lph2W/。CSS 将背景图像大小设置为 200px X 200px,然后 JS 将其更新为 100px X 100px。
回答by Kingsley Mitchell
This worked for me and I hope this helps some one else.
这对我有用,我希望这对其他人有所帮助。
var el = document.getElementById("notification");
el.style.background = 'url(images/Noti.png) no-repeat center center';
el.style.backgroundSize="100% 100%";
If you found this useful please don't forget to vote UP :)
如果您觉得这有用,请不要忘记投票 :)
回答by Kae Cyphet
It appears that using
看来,使用
style.backgroudSize = 300px;
in the place of
代替
style.backgroud-size = 300px;
solves this issue, but i wanted to point out a shorthand version as well
解决了这个问题,但我也想指出一个速记版本
style.background = "url('url_here') repeat fixed /300px";
just remember to keep the background size on the end, as if its added in the middle it seems to break.
只需记住将背景大小保持在最后,就好像它添加在中间一样,它似乎破裂了。