javascript javascript将变量传递给样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6144182/
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
javascript pass variable to style
提问by hobbywebsite
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
好的,链接在那里 ---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.
那么对于我的 html,我只需要插入我的图片。
<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()?
然而,我可以让“document.getElementById 工作。有没有办法在没有按钮的情况下做到这一点......比如 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" />
回答by Oded
You can't pass variables to CSS.
您不能将变量传递给 CSS。
You can, however, use javascript directly to change the image style (including dimensions).
但是,您可以直接使用 javascript 来更改图像样式(包括尺寸)。
回答by ADW
You can use JS to modify CSS, see this question:
可以用JS修改CSS,看这个问题: