Javascript变量为css [英] Javascript variable to css

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

问题描述

我正在处理一个小的html页面。我正在使用javascript来获取屏幕的尺寸。我需要将该变量传递给css样式,如下所示。我怎样才能做到这一点?另外我注意到我需要将px放在值的末尾,如top:100px not top:100。我怎样才能将它添加到我的变量中?感谢您的帮助

I am working on a small html page. I am using javascript to get the dimensions of the screen. I need to pass that variable to a css style like below. How can I do this? Also I notice that I need to put the "px" at the end of the value, like top: 100px not top:100. How can I add that to my variable as well? Thanks for any help

<script type="text/javascript">
    var percent =1;
    var myWidth = Math.round( screen.width * percent);
    var myHeight = Math.round( screen.height * percent);
</script>

<style type="text/css">
    div.content {
margin: auto;
top: myHeight ;
width: myWidth ;
    }
</style>


推荐答案

如果您打算使用 LESS CSS 你可以尝试这个:

If you intend to use LESS CSS you can try out this :

    @percent: 1;
    @height: `Math.round( screen.height * @{percent})`;
    @width: `Math.round( screen.width * @{percent})`;
    div.content {
    margin: auto;
    top: @height;
    width: @width;
    }

如果您打算使用 JQUERY ,可以尝试出这个:

If you intend to use JQUERY you can try out this :

var percent=1;
$("div.content").css('top', Math.round( screen.height * percent)+'px');
$("div.content").width(Math.round( screen.width * percent));

如果您打算使用 JS ,可以试试这个:

If you intend to use JS you can try out this :

var percent=1;
document.querySelector('div.content').style.top = Math.round( screen.height * percent)+'px';
document.querySelector('div.content').style.width = Math.round( screen.width * percent)+'px';

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

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