【问题标题】:How to convert the following jQuery to Javascript for ReactJS?如何将以下 jQuery 转换为 ReactJS 的 Javascript?
【发布时间】:2017-02-10 18:13:22
【问题描述】:

我有一个ReactJS 项目,由于各种原因,我被建议不要使用jQuery,所以我尝试将以下jQuery 转换为JavaScript——它可以平滑地更改背景颜色,同时滚动页面:

$( window ).ready(function() {

    var wHeight = $(window).height();

    $('.slide')
        .height(wHeight)
        .scrollie({
            scrollOffset : -50,
            scrollingInView : function(elem) {

                var bgColor = elem.data('background');

                $('body').css('background-color', bgColor);

            }
        });

    });

CSS:

* { box-sizing: border-box }

body {
    font-family: 'Coming Soon', cursive;
    transition: background 1s ease;
    background: #3498db;
}

p {
    color: #ecf0f1;
    font-size: 2em;
    text-align: center;     
}

a {
    text-decoration: none;
}

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2542/jquery.scrollie.min_1.js"></script>

<div class="main-wrapper">

    <div class="slide slide-one" data-background="#3498db">
        <p>Title</p>
        <center>Go To <a href="#green" style="color:green">Green</a>.</center>  
    </div>

    <div class="slide slide-two" data-background="#27ae60">
        <a name="green">
            <p>Green area</p>
            <center>Go To <a href="#red" style="color:red">Red</a>.</center>
        </a>
    </div>

    <div class="slide slide-three" data-background="#e74c3c">
        <a name="red">
            <p>Red area</p>
            <center>Page over. Hope that was helpful :)</center>
        </a>
    </div>

但是如何转换为JavaScript 以适应ReactJS 项目?

提前谢谢你,一定会接受/支持答案

【问题讨论】:

  • 这里没有人会为您转换整个插件。这不是免费的代码编写或转换服务
  • @charlietfl 我不是要求转换它。我只是在寻求指导......
  • 制作一个 js fiddle 并尝试自己做,在遇到困难的地方发布,人们会更愿意提供帮助。
  • @charlietfl 天哪。到底是什么
  • 我认为您没有意识到您所问的问题并非微不足道,而且这里的问题范围太广

标签: javascript jquery html css reactjs


【解决方案1】:

从 JQuery 更改为 JavaScript 始终是可能的。因为 JQuery 建立在 JavaScript 之上。大多数时候(就像你的情况一样)它甚至没有那么多工作。

我没有更改您的 CSS 或 HTML。所以这只是一些新的 JavaScript。但是,您应该将此脚本放在网站的末尾。

(function() { // create an own scope and run when everything is loaded

  // collect all the slides in this array and apply the correct height
  var slides = document.getElementsByClassName('slide')
  for (slide of slides) slide.style.height = window.innerHeight + 'px'

  // use the native scroll event
  document.addEventListener("scroll", function() {
    // how much have we scrolled already
    var currentOffset = document.documentElement.scrollTop || document.body.scrollTop

    // now check for all slides if they are in view (only one will be)
    for (slide of slides) {
       // 200 is how much before the top the color should change
       var top = slide.getBoundingClientRect().top + currentOffset - 200
       var bottom = top + slide.offsetHeight

      // check if the current slide is in view
      if (currentOffset >= top && currentOffset <= bottom) {
        // set the new color, the smooth transition comes from the CSS tag
        // CSS: transition: background 1s ease;
        document.body.style.background = slide.dataset.background
        break
      }
    }

  })

}())

此外,您可能还想监听 resize 事件,因为到目前为止,当您调整窗口大小时,窗口看起来会有些偏离(这替换了上面代码的 5 行)

  function setSize() {
    for (slide of slides) slide.style.height = window.innerHeight + 'px'
  }
  window.addEventListener("resize", setSize)
  setSize()

解决方案

(function() {
  
  var slides = document.getElementsByClassName('slide')
  function setSize() {
    for (slide of slides) slide.style.height = window.innerHeight + 'px'
  }
  window.addEventListener("resize", setSize)
  setSize()

  document.addEventListener("scroll", function() {
    var currentOffset = document.documentElement.scrollTop || document.body.scrollTop
    
    for (slide of slides) {
       // 100 is how much before the top the color should change
       var top = slide.getBoundingClientRect().top + currentOffset - 100
	   var bottom = top + slide.offsetHeight

      if (currentOffset >= top && currentOffset <= bottom) {
        document.body.style.background = slide.dataset.background
        break
      }
    }
    
  })
  
}())
body {
    font-family: 'Coming Soon', cursive;
    transition: background 1s ease;
    background: #3498db;
}

p {
    color: #ecf0f1;
    font-size: 2em;
    text-align: center;     
}

a { text-decoration: none;
}
<div class="main-wrapper">

    <div class="slide slide-one" data-background="#3498db">
        <p>Title</p>
        <center>Go To <a href="#green" style="color:green">Green</a>.</center>  
    </div>

    <div class="slide slide-two" data-background="#27ae60">
        <a name="green">
            <p>Green area</p>
            <center>Go To <a href="#red" style="color:red">Red</a>.</center>
        </a>
    </div>

    <div class="slide slide-three" data-background="#e74c3c">
        <a name="red">
            <p>Red area</p>
            <center>Page over. Hope that was helpful :)</center>
        </a>
    </div>

【讨论】:

  • @JoKo 这个答案对你有帮助吗?没有,怎么可能?
【解决方案2】:

plugin 你指的是链接an example 来自他们的自述文件,其中包括一个指向newer version 的链接,它使用了this other plugin 使用 jQuery,实际上确实使用了 jQuery你想让它做什么,我想。它被称为in-view,对我来说看起来非常好(无论是功能还是代码)。

它的用法与您目前正在做的非常相似。从上面链接的较新示例中:

var $target = $('.wrapper');
inView('.section').on('enter', function(el){
  var color = $(el).attr('data-background-color');
  $target.css('background-color', color );
});

我确实意识到我在某种程度上没有回答这个问题,因为这不是 jQuery 到 vanilla-JS 的指南,但我确实认为知道有人已经为你做了这件事会有所帮助。

【讨论】:

    【解决方案3】:

    应该会给你一些想法。

    var wHeight = window.innerHeight;
    

    在 javascript 中选择元素: 在浏览器上打开检查元素、控制台选项卡并输入:

    document.get
    

    它会提示你得到什么

    获取元素样式:

     var elem1 = document.getElementById("elemId");
     var style = window.getComputedStyle(elem1, null);
    

    设置属性:

     document.body.style.setProperty(height`, wHeight  +"px");
    

    以下是您可以进行的一些修改,正如人们评论的那样,我并不是想教您如何做,而是想给您一些开始:

     // $( window ).ready(function() { //remove this
    
    var wHeight = $(window).height(); // USe this instead: var wHeight = window.innerHeight;
    
    $('.slide') //instead of selecting with jquery "$('.slide')"  select with:  Javascript var x = document.getElementsByClassName("example") ;
      .height(wHeight) // Here you are chaining methods, read this article https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html
      .scrollie({
        scrollOffset : -50,
        scrollingInView : function(elem) {
    
          var bgColor = elem.data('background'); //var bgColor = window.getComputedStyle(elem, null);
    
          $('body').css('background-color', bgColor); //document.body.style.background = bgColor;
    
        }
      });
    
     // }); //remove this
    

    为了……在

    var t = document.getElementsByClassName('slide')
    console.log(typeof t) //object
    
    for (var prop in t) {
     console.log('t.' + prop, '=', t[prop]);
     // output is index.html:33 t.0 = <div class=​"slide slide-one" data-      background=​"#3498db">​…​</div>​
     // output is index.html:33 t.1 = <div class=​"slide slide-two" data- background=​"#27ae60">​…​</div>​
     // output is index.html:33 t.2 = <div class=​"slide slide-three" data-background=​"#e74c3c">​…​</div>​<a name=​"red">​…​</a>​</div>​
    // output is index.html:33 t.length = 3
    // output is index.html:33 t.item = function item() { [native code] }
    // output is index.html:33 t.namedItem = function namedItem() { [native code] }
    

    }

    【讨论】:

    • 在我接受答案并投票之前,您介意展示一下它与我提供的代码的关系吗?
    • 真的很感谢你们的cmets!帮助我理解和学习。 scrollie({ scrollOffset : -50, scrollingInView : function(elem)的情况,应该怎么处理?
    • 真的很棒的阅读!所以我的问题是,我应该如何重新定义 '.slide' 以便它按照建议返回一个对象?
    • 编辑了一个答案,在使用 React 之前,您需要阅读更简单的 Javascript。
    • 看看对象是如何返回的!谢谢你。 scrollie({ scrollOffset : -50, scrollingInView : function(elem)怎么样?仍然不确定应该如何处理。
    猜你喜欢
    • 2019-06-28
    • 2016-03-31
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    相关资源
    最近更新 更多