访问Javascript变量

时间:2014-11-05 19:23:18

标签: javascript html

我试图根据屏幕宽度设置段落样式,基本上是为了容纳手机。 html有左右几个缩进。目前它们是硬编码的,但在移动屏幕上看起来并不是很好。我已尝试声明变量,然后根据screen.width设置它们,但它没有工作。基本上我想要点什么:

<style>
var IndentLeft = 150px;
var IndentRight= 250px;

if (screen.width <=500) {IndentLeft=50px; IndentRight=50px;}
.para {margin-left : IndentLeft; margin-right: IndentRight}
</style>

然后像这样使用它:     <p class="para">等等等等

3 个答案:

答案 0 :(得分:2)

应该使用 MediaQueries 。 看看:https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries

在你的情况下,CSS应该是这样的。

@media (max-width: 500px){
  .para{
    margin-left: 150px;
    margin-right: 250px;
  }
}

如果你想使用变量,你需要更高级的东西,比如 CSS预处理器 ex。 LESSSASS,但首先您需要很好地学习CSS。

答案 1 :(得分:0)

首先,您需要脚本标记,而不是样式标记。其次,如果您要将变量设置为字符串值,则需要将它们括在引号中。

这是未经测试的代码,但应该给你一个想法。使用jQuery选择器,所以你需要在头标记中使用它:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

以下是正文标记末尾的代码:

<script type="text/javascript">
    $("document").ready(function(){
        var IndentLeft = "150px";
        var IndentRight= "250px";

        if (screen.width <=500) {IndentLeft="50px"; IndentRight="50px";}
        $(".para").each(function(){
            $(this).css("margin-left", IndentLeft);
            $(this).css("margin-right", IndentRight);
        });
    });
</script>

答案 2 :(得分:0)

你不能在CSS代码中使用Javascript代码。

您可以为不同的情况指定不同的样式:

<style>
.para { margin-left: 150px; margin-right: 250px; }
.narrow .para { margin-left: 50px; margin-right: 50px; }
</style>

然后在body元素内部(以便在脚本运行时它存在),您可以根据屏幕大小放置一个脚本,将类添加到正文中。这样会影响其中包含class="para"的所有元素:

<script>
if (screen.width <= 500) document.body.className = 'narrow';
</script>