Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

html - Javascript variable to css

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }

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));

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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...