仅使用Javascript显示/隐藏滚动元素 [英] Show/Hide Element on Scroll Using Javascript Only

查看:141
本文介绍了仅使用Javascript显示/隐藏滚动元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个非常轻的wp主题。边栏有几个小部件,只填充两页长度。现在,我想利用边栏的其余部分,当小部件在用户向下滚动时看不见。这很棒,特别是如果文章很长。

I am building a very light wp theme. The sidebar has few widgets, filling two page length only. Now, I want to utilize the rest of the sidebar when the widgets are out of sight as the user scrolls down. This would be great especially if the article is very long.

使用jquery的浮动元素是常见的。正如我所说的,这应该是非常轻的主题。 jQuery很重。

Floating element using jquery is common. As what I've said, this is supposed to be very light theme. jQuery is very heavy. Is it possible to use javascript only, even just appear and disappear, to display an element at certain page length?

注意:这个主题是响应式的。

Note: This theme is responsive.

[UPDATE]问题解决!非常感谢。

[UPDATE] Problem solved! Thanks to all.

我为jQuery保存了100kb的带宽。

I saved 100kb+ bandwidth for jQuery.

新脚本。

<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>


推荐答案

要完全回答您的问题,您可以使用: p>

To FULLY answer your question you could use:

window.onscroll(function() {
    document.getElementById("target-id").style.display = "block";
});

滚动窗口时触发该函数。这是一个好主意,把这个函数内部拖动的div,这种方式,如果用户只是滚动页面,这个函数不被调用。如果你正在寻找一个特定的数量为窗口滚动,例如显示额外的divs当窗口滚动400px,这里有一个很好的答案:当窗口滚动到某些位置时触发事件

The function is triggered when the window is scrolled. It would be a good idea to put this function inside of your function for dragging the div, that way this function isn't called if the user is simply scrolling the page. If you are looking for a specific amount for the window to scroll, for example "show the additional divs when the window is scrolled 400px", there is a great answer for that here: Trigger events when the window is scrolled to certain positions

我建议使用我提供的链接来设置位置,因为window.scroll被立即调用,可能不是你想要的。

I recommend using the link I've provided to set a position because window.scroll is called immediately and might not be quite what you're looking for.

这篇关于仅使用Javascript显示/隐藏滚动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆