JS-正在更改.top属性
JS - Changing .top property
我有一个div,我想更改它的"top"属性。它目前是在CSS表中设置的,但是当我的功能完成后,我希望它能改变。
这是我试图使用的代码,但它没有任何作用:
<script>
function reposition(){
var windowWidth = window.innerWidth;
if (windowWidth > 667) {
document.getElementById("SubmitAFilm").style.top = "100px";
}
}
window.addEventListener("resize",changeFontSize,false);
</script>
将您在addEventListener
中应用的函数更改为reposition
。此外,您还需要有position: absolute
才能使top
值起作用。
function reposition() {
var windowWidth = window.innerWidth;
if (windowWidth > 667) {
document.getElementById("SubmitAFilm").style.top = "100px";
}
}
window.addEventListener("resize", reposition, false);
#SubmitAFilm {
position: absolute;
}
<div id="SubmitAFilm">Submit a Film</div>
您应该在要移动的div上设置position:absolute。
下面是一个演示:https://jsbin.com/pevomekezu/1/edit?html,输出
样本代码:
<div id="SubmitAFilm" style="position:absolute">thefilm</div>
<script>
function reposition(){
var windowWidth = window.innerWidth;
if (windowWidth > 667) {
document.getElementById("SubmitAFilm").style.top = "100px";
console.log('changetop')
}
else {
document.getElementById("SubmitAFilm").style.top = "0px";
}
console.log('reposition')
}
window.addEventListener("resize",reposition,false);
</script>
编辑:第二个解决方案:如果你不想使用绝对定位,你可以在脚本中使用"marginTop"而不是"top"。结果会是你想要的。
相关文章:
- jQuery控制台错误:无法读取属性'top'的未定义
- Jquery scrollTop动画不工作"无法读取属性'top'无风
- 使用javascript动态计算top属性
- 无法仅在活动服务器上读取未定义错误的属性“top”
- 正在尝试滚动页面:未捕获类型错误:无法读取属性'top'的未定义
- IE7/8未添加css属性'top'动态地作为内联样式
- 未捕获的类型错误:无法读取属性'top'的未定义
- 未捕获的类型错误:无法读取未定义的属性“top”
- 为什么我会收到错误:未捕获的类型错误:无法使用此代码读取 null 的属性“top”
- JavaScript 运行时错误:无法获取未定义或空引用的属性“top”
- 无法读取未定义的链接 href 的属性“top”
- 未捕获的类型错误:无法读取未定义错误的属性“top”
- 偏移 JavaScript 滚动:无法读取未定义错误的属性“top”
- 如何根据php标题的长度调整margin-top属性
- TypeError:无法读取属性'top'的未定义
- 无法读取属性'top'未定义的Jquery/javascript
- 制作一个带有切换的菜单,该菜单可以使用top属性设置动画
- Jquery .animate()方法似乎不能与css top属性一起工作
- 为什么,当我使用Javascript来绝对定位某个东西时,它是“左”的呢?和“;top"属性总是0px
- JS-正在更改.top属性