我正在使用HC-Sticky JavaScript 插件并尝试使用记录 reinit
的方法,但我不明白如何运行它。
这是一个CodePen,显示了一个非常基本的设置和在初始化后立即运行该方法的尝试reinit
,但控制台总是说
reinit 函数未定义
在这种情况下,您通常如何运行方法?
将您的 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();
使用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>
使用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>