![](/img/trans.png)
[英]How to show only one element ande hide other element using javascript?
[英]Show/Hide Element on Scroll Using Javascript Only
我正在建立一个非常轻便的wp主题。 侧边栏只有几个小部件,仅占两个页面的长度。 现在,当小部件在用户向下滚动时看不见时,我想利用侧边栏的其余部分。 特别是如果文章很长,那会很棒。
使用jquery的浮动元素很常见。 就像我说的那样,这应该是很轻的主题。 jQuery很重。 是否可以仅使用javascript,甚至只是出现和消失,以一定的页面长度显示元素?
注意:此主题是响应式的。
[更新]问题已解决! 谢谢大家。
我为jQuery节省了100kb +的带宽。
作为其他参考,这里是新脚本。
<script defer type="text/javascript">var width = window.innerWidth || document.documentElement.clientWidth;
//Trigger the script only on browser width above 1150px. Recommended on responsive websites
if (width > 1150){ function testScroll(ev){
//Will set the position to FIXED with TOP=80px when user scrolls 850px below.
if(window.pageYOffset>850){document.getElementById("targetID").style.position = "fixed";document.getElementById("targetID").style.top = "80px";}
//Will set the position to ABSOLUTE with TOP=AUTO when user scrolls to top just above 850px line
else {document.getElementById("targetID").style.position = "absolute";document.getElementById("targetID").style.top = "auto";};
window.onscroll=testScroll; };
</script>
如果您不使用任何第三方JavaScript(例如jQuery),请使用它:
document.getElementById('target-id').style.display = 'none'; // hide it
document.getElementById('target-id').style.display = 'block'; // show it (for block element, eg: div)
document.getElementById('target-id').style.display = 'inline'; // show it (for inline element, eg: span)
document.getElementById("target-id").style.visibility = "visible"; //To show the element.
您可以使用常规Javascript完成此操作:
<script>
function scrollFunction() {
document.getElementById("target-id").style.visibility = "hidden"; //To hide the element.
}
window.onscroll = scrollFunction;
</script>
要完全回答您的问题,您可以使用:
window.onscroll(function() {
document.getElementById("target-id").style.display = "block";
});
滚动窗口时触发该功能。 最好将此函数放在函数中以拖动div,这样,如果用户只是滚动页面,就不会调用此函数。 如果您要为窗口滚动查找特定的数量,例如“在窗口滚动400px时显示额外的div”,那么这里有一个很好的答案: 在窗口滚动到特定位置时触发事件
我建议使用我提供的链接来设置位置,因为window.scroll会立即被调用,可能与您要找的不完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.