JS:从部分中删除类

时间:2017-02-21 20:06:07

标签: javascript

我在我的网站上使用视差效果,但是当屏幕较小时,背景图像开始被切断一点。我决定只在桌面上使用视差效果,并将其从其他较小的设备中移除。

例如我有3个部分

<section class="bg1 parallax"></section> 
<section class="bg2 parallax"></section> 
<section class="bg3 parallax"></section>

CSS中没有描述视差类,只是为了让JavaScript知道应该包含哪个部分视差而添加它。

我的问题

有人有一个脚本可以删除课程&#34; parallax&#34;如果屏幕宽度小于例如:1280px?

如果宽度大于1280px

<section class="bg1 parallax"></section>

否则

<section class="bg1"></section>

3 个答案:

答案 0 :(得分:0)

我还没有测试过,但这应该会让你朝着正确的方向前进......

import requests

  class Geckoboard(object):
          def __init__(self, api_key):
                  self.api_key = api_key

          def create(self, name, schema):
                  url = 'https://api.geckoboard.com/datasets/%s' % name
                  return requests.put(url, json=schema, auth=(self.api_key, ''))

          def delete(self, name):
                  url = 'https://api.geckoboard.com/datasets/%s' % name
                  return request.delete(url, auth=(self.api_key, ''))

          def replace(self, name, data):
                  url = 'https://api.geckoboard.com/datasets/%s/data' % name
                  return requests.put(url, json=data, auth=(self.api_key, ''))

          def append(self, name, data):
                  url = 'https://api.geckoboard.com/datasets/%s/data' % name
                  return requests.post(url, json=data, auth=(self.api_key, ''))

答案 1 :(得分:0)

看起来有点hacky,但你可以这样做:

// closure so we don't pollute global scope. This should be run at the bottom of the page so that it can find all of the parallax elements on the page
(function(){
    var previous_width = 0;
    var cutoff = 1280;
    var $parallax_elements = $('.parallax');
    function check_width() {
        var current_width = document.body.clientWidth;
        // if the document has gone from narrow to wide, re-enable parallax
        if (current_width > cutoff && previous_width <= cutoff) {
             $parallax_elements.addClass('parallax');
        }
        // if the document has gone from wide to narrow, disable parallax
        else if (current_width <= cutoff && previous_width > cutoff) {
             $parallax_elements.removeClass('parallax');
        }
        // store the current width for the next check
        previous_width = current_width;
    }

    // run it every time the window resizes
    $(window).resize(check_width);

    // run it once to initialize
    check_width();
})();

答案 2 :(得分:0)

在控制台中尝试过,似乎有效。

if(window.innerWidth < 1280){
    var parallaxes = document.getElementsByClassName('parallax');
    while(parallaxes[0]){
       parallaxes[0].classList.remove('parallax');
    }
}