【问题标题】:Change css positioning using javascript使用 javascript 更改 css 定位
【发布时间】:2014-07-18 11:44:42
【问题描述】:

此代码按我的预期完美运行,但问题是当我刷新页面时,t_con 保持在绝对值,这应该是固定的,当我将窗口大小调整为小于 980 像素时,它就像我需要的那样是绝对值,如果我再次调整大小超过 980 像素,它会被修复。

我需要它从一开始就保持固定。一开始我不知道为什么它是绝对的。

HTML 代码

<div id="t_con">
<div id="t">

</div>
</div>

CSS 代码

#t_con{
width:100%;
position:absolute;
top:0;
}
#t{
margin:0px auto 0 auto;
background-color:#976398;
width:980px;
height:30px;
}

Javascript 代码

window.onresize = function(){
var pos = window.outerWidth < 980 ? 'absolute' : 'fixed';
document.getElementById('t_con').style.position = pos;
}window.onresize=function(){
var header=document.getElementById('t');
var window_width = document.body.offsetWidth;
if(window_width < 980){
header.style.position="absolute";
}else{
header.style.position="fixed";
}
}

谁能告诉我在这里做错了什么。我不想为此使用 jQuery。 所以请不要建议它。我不喜欢 jQuery 的原因是它已经占用了 90kb 加上我们尝试执行的代码。

【问题讨论】:

  • t_con.innerWidth 到底是什么t_con,你把它命名为header,你应该检查一下window,对吧?
  • 我需要换吗??/
  • 得到了答案,伙计们......我在代码中犯了一个错误,adeno 注意到了。
  • 那么请随时接受答案。

标签: javascript css css-position


【解决方案1】:
window.onresize = function(){
    var pos = window.outerWidth < 980 ? 'absolute' : 'fixed';
    document.getElementById('t_con').style.position = pos;
}

FIDDLE

【讨论】:

  • 如果我调整窗口大小,它不会变为绝对窗口。它保持固定。
  • 你打错了,它是getElementById,最后一个d是小写的。
  • 哦,谢谢你,我是个白痴,我犯了这个简单的错误,差点因为不工作而哭泣。非常感谢。
  • 你能重新看看我的问题吗@adeneo
【解决方案2】:
window.onresize=function(){
var header=document.getElementByID('t_con');
var window_width = document.body.offsetWidth;
if(window_width < 980){
    header.style.position="absolute";
}else{
    header.style.position="fixed";
}
}

【讨论】:

  • 你能重新看看我的问题吗@adidi
猜你喜欢
  • 1970-01-01
  • 2022-06-30
  • 2013-06-26
  • 2010-10-08
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
  • 2018-12-12
  • 1970-01-01
相关资源
最近更新 更多