use*_*793 13 html javascript css jquery
请告诉我如何以最正确的方式做到这一点.
HTML:
<div id="fixed-red" class="fixed-red"></div>
<div id="fixed-green" class="fixed-green"></div>
<div id="fixed-blue" class="fixed-blue"></div>
<div id="red" class="red"></div>
<div id="green" class="green"></div>
<div id="blue" class="blue"></div>
Run Code Online (Sandbox Code Playgroud)
CSS:
html,body{
height:100%;
}
.fixed-red,.fixed-green,.fixed-blue{
width:30px;
height:30px;
position:fixed;
top:10px;
left:10px;
background:#333;
}
.fixed-green{
top:50px;
}
.fixed-blue{
top:90px;
}
.red-active{
background:#f00;
}
.green-active{
background:#0f0;
}
.blue-active{
background:#00f;
}
.red,.green,.blue{
width:100%;
height:100%;
}
.red{
background:#900;
}
.green{
background:#090;
}
.blue{
background:#009;
}
Run Code Online (Sandbox Code Playgroud)
我想添加/删除red/green/blue-active类的fixed-red/green/blue的div当用户打开/关闭red,green或bluediv的(当它们是可见的),所以小的div将与大,显示的div的颜色分别强调当用户在他们.
谢谢!
Agn*_*ney 15
我不得不稍微调整一下代码,以便代码可以更干.类现在被color类替换.
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on('resize scroll', function() {
$('.color').each(function() {
var activeColor = $(this).attr('id');
if ($(this).isInViewport()) {
$('#fixed-' + activeColor).addClass(activeColor + '-active');
} else {
$('#fixed-' + activeColor).removeClass(activeColor + '-active');
}
});
});Run Code Online (Sandbox Code Playgroud)
html,
body {
height: 100%;
}
.fixed-red,
.fixed-green,
.fixed-blue {
width: 30px;
height: 30px;
position: fixed;
top: 10px;
left: 10px;
background: #333;
}
.fixed-green {
top: 50px;
}
.fixed-blue {
top: 90px;
}
.red-active {
background: #f00;
}
.green-active {
background: #0f0;
}
.blue-active {
background: #00f;
}
.color {
width: 100%;
height: 100%;
}
#red {
background: #900;
}
#green {
background: #090;
}
#blue {
background: #009;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fixed-red" class="fixed-red red-active"></div>
<div id="fixed-green" class="fixed-green"></div>
<div id="fixed-blue" class="fixed-blue"></div>
<div id="red" class="color"></div>
<div id="green" class="color"></div>
<div id="blue" class="color"></div>Run Code Online (Sandbox Code Playgroud)
这是一个工作的小提琴
https://jsfiddle.net/BoyWithSilverWings/ds9x55z7/
| 归档时间: |
|
| 查看次数: |
5001 次 |
| 最近记录: |