仅执行一次滚动事件

时间:2019-08-30 13:39:40

标签: javascript jquery

我在尝试将css添加到1500像素后滚动上的pop-overlay类时遇到问题,但是只有一次。任何帮助将不胜感激。

import requests
def get_response(url):
    print('Input URL:\n\t %s'%(url))
    response = requests.get(url)
    return response

def get_response_dont_redirect(url):
    print('Input URL:\n\t %s'%(url))
    response = requests.get(url, allow_redirects=False)
    return response

def check_response_status(response):
    status = response.status_code
    if status == 200:
        print(('Final URL:\n\t %s')%response.url)
        print('Status Code: %s / OK'%(status))
        return 'ok'
    if status == 302:
        print(('Final URL:\n\t %s')%response.url)
        print('Status Code: %s / Redirected'%(status))
        return 'redirected'
    if status == 404:
        print('Status Code: %s / Access Denied'%(status))
        return 'denied'

def save_image(response, status_code):
    if status_code ==302:
        with open('image_wanted.jpg', 'wb') as f:
            print('\nSaving image desired under "image_wanted.jpg"...\n')
            f.write(response.content)
    elif status_code == 200:
        with open('image_redirect.jpg', 'wb') as f:
            print('\nSaving image redirected under "image_redirect.jpg"...\n')
            f.write(response.content)
    elif status_code == 111:
        with open('image_normal.jpg', 'wb') as f:
            print('\nSaving image normal under "image_normal.jpg"...\n')
            f.write(response.content)

def case_1_comments():
    print('-------------------------------------------------------------------')
    print('#Comments:')
    print('# This is the ideal situation where I can simply download an image')
    print('-------------------------------------------------------------------')
def case_2_comments():
    print('-------------------------------------------------------------------')
    print('#Comments:')
    print('# Notice that despite the status code being 200, the input URL and final URL is different ')
    print('\t>I am definitely being redirected')
    print('\t>I get a dummy image from the redirected page')
    print('-------------------------------------------------------------------')
def case_3_comments():
    print('-------------------------------------------------------------------')
    print('#Comments:')
    print('# Here I have set the restriction of "allow_redirects=False" yet I get status code:302 ')
    print('\t>Somehow the input and final URL is the same')
    print('\t>The image saved is perpetually loading...')
    print('-------------------------------------------------------------------')

print("\n\n--- Case 1: Standard procedure ---\n")
url = 'https://i5.walmartimages.ca/images/Large/094/514/6000200094514.jpg'
response = get_response(url)
status = check_response_status(response)
save_image(response, 111)
case_1_comments()

print("\n\n--- Case 2: without 'allow_redirects=False' restriction ---\n")

url = 'http://photo.yupoo.com/evakicks/6b3a8a2a/small.jpg'
response = get_response(url)
status = check_response_status(response)
save_image(response, 200)
case_2_comments()

print("\n\n--- Case 3: with 'allow_redirects=False' restriction ---\n")

url = 'http://photo.yupoo.com/evakicks/6b3a8a2a/small.jpg'
response = get_response_dont_redirect(url)
status = check_response_status(response)
save_image(response, 302)
case_3_comments()

3 个答案:

答案 0 :(得分:0)

尝试一下。

jQuery(window).on("scroll", function(event) {
  if (jQuery(this).scrollTop() > 1500) {
    jQuery('.popbox-overlay').css('display', 'block');
    jQuery(window).scrollTop(0);
  };
  jQuery(window).off("scroll")
});

答案 1 :(得分:0)

您只需要将off()调用移至if条件。下面修改后的逻辑使用命名函数在窗口上创建滚动事件侦听器。它还缓存$(window),因此只能创建一次。然后在逻辑中,当显示了叠加层时,它通过对该方法执行off()来删除该事件侦听器。这样,仅该事件侦听器将被删除。您可以简单地off('scroll')进行操作,但这可能会删除比您想要的更多的事件侦听器。

我还为叠加层添加了一个click事件监听器,因此您可以单击它以使其再次隐藏,并看到滚动到底部时它不会再次显示。

(function($, window, undefined){
  let $popboxOverlay = $('.popbox-overlay').on('click', function(e){
    $popboxOverlay.hide();
  });

  let $window = $(window).on('scroll', function showPopboxOverlay(e){
    if ($window.scrollTop() > 1500) {
      $popboxOverlay.show();
      $window.scrollTop(0);
      $window.off('scroll', showPopboxOverlay);
    }
  });
}(jQuery, window));
body {
  min-height: 2000px;
}

.popbox-overlay {
  position: fixed;
  top: 5vh;
  left: 5vw;
  width: 90vw;
  height: 90vh;
  
  background-color: rgb(64, 64, 192);
  color: white;
  
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Stuff</span>

<div class="popbox-overlay">
  Other Stuff
</div>

答案 2 :(得分:0)

解决此问题的最佳方法是使用 Intersection Observer (IO)。这是为像您​​这样的用例设计的:它监视一个元素并在它进入(或离开)视口时触发一个函数。它甚至支持检查一个元素是否与另一个元素相交。

首先,您必须为 IO 设置选项并对其进行初始化:

let options = {
  rootMargin: '0px',
  threshold: 1.0
}

let observer = new IntersectionObserver(callback, options);

let targets = document.querySelectorAll('popbox-overlay'); // get each popbox-overlay
targets.forEach(target => { // for each overlay
  observer.observe(target); // we observe it
});
// the callback we setup for the observer will be executed now for the first time
// it waits until we assign a target to our observer (even if the target is currently not visible)

最后一步是定义元素进入视图后实际发生的情况:

let callback = (entries, observer) => {
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   Your popbox-overlay is in the viewport, do something with it
  });
};

如果您只需要触发一次,您也可以unobserve an element

支持不支持此功能的旧浏览器 (IE 11) 的 polyfill from w3c exists