如何从HC-Sticky插件运行方法?

时间:2018-06-26 21:37:15

标签: javascript jquery html css hcsticky

我正在使用HC-Sticky JavaScript插件,并尝试使用documented reinit方法,但是我不知道如何运行它。

这是CodePen,显示了非常基本的设置,并尝试在初始化后立即运行reinit方法,但控制台始终表示

  

未定义reinit函数

在这种情况下通常如何运行方法?

1 个答案:

答案 0 :(得分:1)

将HC-Sticky实例存储在变量中,然后可以使用HC-Sticky的API:

var sticky = new hcSticky('.this-sticks', {
    stickTo: 'main'
});    

sticky.reinit();

通过jQuery.data(...)访问它:

jQuery('.this-sticks').hcSticky({
    stickTo: 'main'
});

jQuery('.this-sticks').data('hcSticky').reinit();

示例1:

使用new hcSticky(...)

jQuery(document).ready(function() {
  var sticky = new hcSticky('.this-sticks', {
    stickTo: 'main'

  });      
  sticky.reinit();
});
body {
  margin-top: 300px;
}

header {
  height: 300px;
  background: black;
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
}

section {
  height: 100vh;
  background: #ccc;
}

footer {
  height: 400px;
  background: black;
}

.this-sticks {
  background: blue;
  height: 100px;
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>HC Sticky Example</title>
</head>
<body>
  <div>
  <header></header>
  <main>
    <section class="this-sticks">sticky</section>
    <section></section>
  </main>
  <footer></footer>  
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://rawgit.com/somewebmedia/hc-sticky/master/dist/hc-sticky.js"></script>
</body>
</html>


示例2:

使用jQuery(...).hcSticky(...)

jQuery(document).ready(function() {
  jQuery('.this-sticks').hcSticky({
    stickTo: 'main'
  });
  
  jQuery('.this-sticks').data('hcSticky').reinit();
});
body {
  margin-top: 300px;
}

header {
  height: 300px;
  background: black;
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
}

section {
  height: 100vh;
  background: #ccc;
}

footer {
  height: 400px;
  background: black;
}

.this-sticks {
  background: blue;
  height: 100px;
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>HC Sticky Example</title>
</head>
<body>
  <div>
  <header></header>
  <main>
    <section class="this-sticks">sticky</section>
    <section></section>
  </main>
  <footer></footer>  
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://rawgit.com/somewebmedia/hc-sticky/master/dist/hc-sticky.js"></script>
</body>
</html>