javascript pass variable to style

一曲冷凌霜 提交于 2019-12-11 20:01:34

问题


screen_w = window.innerWidth;
screen_h = window.innerHeight;

to get the window deminsions and then set it to a variable. Is there a way to take that variable and then use it in my style?

Such as:

img
{
  width:screen_w;
  height:screen_h;
}

I have tried

<script type="text/javascript"> 
<style>
img..
</style>
</script>

but that doesn't seem to work.. is this even possible or is there some other way to pass a variable?

Thanks in advance.

///Added

Ok so the Link down there ---v

Is discussing making a node that is your "style"

<script type="text/javascript">

var head = document.getElementsByTagName('head')[0],
    style = document.createElement('style'),
    rules = document.createNode('img { width:screen_w; height:screen_h; }');

style.type = 'text/css';
if(style.styleSheet)
    style.styleSheet.cssText = rules.nodeValue;
else style.appendChild(rules);
head.appendChild(style);

</script>

so then for my html I just have to insert my picture.

<img src="slide1.jpg">

but its still not quite passing somehow.

I can however get the "document.getElementById to work. Is there a way to do this without a button.. like onLoad()?

function changeSize()
{
document.getElementById("picture").height= screen_h;
document.getElementById("picture").width= screen_w;
}
</script>

</head>

<body>

<img id="picture" src="slide1.jpg" width="300" height="98" />
<br /><br />
<input type="button" onclick="changeSize()" value="Change size of image" />

回答1:


You can use JS to modify CSS, see this question:

How to create a <style> tag with Javascript




回答2:


You can't pass variables to CSS.

You can, however, use javascript directly to change the image style (including dimensions).



来源:https://stackoverflow.com/questions/6144182/javascript-pass-variable-to-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!