【问题标题】:Why can't I set top and left to $(window).width() * number为什么我不能将 top 和 left 设置为 $(window).width() * number
【发布时间】:2013-05-16 09:30:18
【问题描述】:

在我的css文件中,我设置了

#background_layer0{
   width: $(window).width();
   height: $(window).height();
}

而且它有效。但是,正如我设置的那样

#background_layer0{
   top: $(window).width() * 0.5;
   left: $(window).height() * 0.6;
}

它不能工作。我看不出这两种属性之间有任何区别:
width , heighttop left。 请纠正我的错误并解释原因。另外,希望大家可以给我一些阅读参考。

更新:我需要将网页部署到其他设备,例如:手机。 如果我只使用百分比作为值,它可以工作吗?

【问题讨论】:

  • 您不能在 CSS 文件中使用 JavaScript。你究竟是如何让第一个例子工作的?
  • 通过.css()函数来实现
  • 嗯...为什么第一个有效...如何设置元素大小以固定CSS文件中的屏幕宽度和高度...
  • 没有。使用百分比作为答案显示。
  • 在“css”中使用javascript的唯一方法是使用less(和/或sass?),但即使那样你也不能使用jQuery:http://lesscss.org

标签: html css


【解决方案1】:

使用单独的 JavaScript 文件或将其包含在脚本标记中

$('#background_layer0').css('top', function() {
    return $(window).width() * 0.5;
});

$('#background_layer0').css('left', function() {
    return $(window).height() * 0.6;
});

【讨论】:

  • 正如 Juhana 所说,您不需要此代码中的匿名函数。只需使用$('#background_layer0').css('top', $(window).width() * 0.5);
  • 一旦我需要计算一些东西,我更喜欢匿名函数,因为它具有更好的可读性。虽然这个例子还是很简单的。
  • 等一下,匿名函数后你忘记)了~请更新。
【解决方案2】:

您可以简单地使用百分比:

#background_layer0{
width: 100%;
height: 100%;
}

#background_layer0{
top: 50%;
left: 60%;
}

【讨论】:

  • 为什么是匿名函数? .css('left', $(window).height() * 0.6) 也可以。
  • height: 100% 作为 body 元素的子元素,与 $(window).height() 不同
【解决方案3】:

所以,在 CSS 中,不能使用 $(window).height()$(window).width(),必须以百分比、像素等形式指定(必须是绝对值)

要使对象的宽度与窗口的宽度和高度相同,必须使用javascript/jquery

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2017-10-31
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 2011-05-25
    相关资源
    最近更新 更多