将新值与最新的JavaScript进行比较

时间:2017-03-12 18:16:35

标签: javascript

我想定义一个var res = 500,然后将其与其他一些值进行比较,如果另一个值大于LATEST res,则将其保存在res上。问题是,在每次比较中,JavaScript都使用最初定义的值,即var res = 500。如何将其与最新值进行比较而非初始值?

我的代码:(在页面上滚动。正如您在红色区域中看到的那样,res反复跳转到500)

window.onscroll = function() {
      var px = window.scrollY;
      var x = document.getElementsByClassName("sidebar");
      var body = document.body,
        html = document.documentElement;
      var res = 500;
      var pxd = px / 100;
      if (px > 500 && pxd === parseInt(pxd, 10)) {
        if (px > res) {
          res = px;
        }
      }
      if (px > 500 - html.clientHeight) {
        x[0].style.position = "fixed";
        x[0].style.bottom = "10px"
      }

      document.getElementById("text").innerHTML ="res:" + res;
    }
.content {
  height: 10000px;
  width: 100px;
  background-color: blue;
  float: right
}

.sidebar {
  height: 500px;
  width: 100px;
  background-color: red;
  float: left;
  position: static
}
<h1>SCROLL THE PAGE</h1>

<div class="content">

</div>

<aside class="sidebar">
  <p id="text" style="padding-top:400px">res:</p>
</aside>

2 个答案:

答案 0 :(得分:1)

这是因为您在每个<header> <section> <div> <h1 class="edit" contenteditable="true" title="Edit your trip name">Trip Name</h1> <h3 class="edit" contenteditable="true" title="Edit your country name"> Country Name</h3> <a href="" class="cd-btn" onclick="saveEdits()">Save</a> </div> </section> </header> <section> <h2 title="Anything to add?">Trip Foucs</h2> <div class="edit" contenteditable="True" title="Anything to add?"></div> </section> <script> function saveEdits() { //get the editable element var editElem = (document.getElementsByClassName("edit")); //get the edited element content var userVersion = editElem.innerHTML; //save the content to local storage localStorage.userEdits = userVersion;} function checkEdits() { //find out if the user has previously saved edits if(localStorage.userEdits!=null) (document.getElementsByClassName("edit")).innerHTML =localStorage.userEdits;} </script> 事件上设置了var res = 500;。您需要在onScroll功能之外设置var res = 500;。见下面的例子:

window.onscroll
var res = 500;
window.onscroll = function() {
      var px = window.scrollY;
      var x = document.getElementsByClassName("sidebar");
      var body = document.body,
        html = document.documentElement;
      var pxd = px / 100;
      if (px > 500 && pxd === parseInt(pxd, 10)) {
        if (px > res) {
          res = px;
        }
      }
      if (px > 500 - html.clientHeight) {
        x[0].style.position = "fixed";
        x[0].style.bottom = "10px"
      }

      document.getElementById("text").innerHTML ="res:" + res;
    }
.content {
  height: 10000px;
  width: 100px;
  background-color: blue;
  float: right
}

.sidebar {
  height: 500px;
  width: 100px;
  background-color: red;
  float: left;
  position: static
}

答案 1 :(得分:1)

正如您所写,每次滚动页面时res等于500.

你只需要把

var res = 500;

out of the window.onscroll function