javascript传递变量为样式 [英] javascript pass variable to style

查看:148
本文介绍了javascript传递变量为样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

如:

img
{
  width:screen_w;
  height:screen_h;
}

我试过了

<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?

提前感谢。

///添加

好,所以链接在那里--- v

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>

那么对于我的HTML,我只需要插入我的照片。

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

<img src="slide1.jpg">

但仍然不能通过某种方式。

but its still not quite passing somehow.

我可以得到document.getElementById工作。有没有一个方法来做这个没有按钮..像onLoad()?

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" />


推荐答案

您可以使用JS修改CSS,请参阅以下问题:

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

如何使用JavaScript创建< style>标签

这篇关于javascript传递变量为样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆