详细信息:
情况=第一个自己的js函数仍然无法正常工作,
英语技能=糟糕,
explanation =以下代码,
问题=只有函数“ fnElementVisible”的最后一次调用有效,
目标=了解我的(想法)错误;
解释代码:
$(function() {
var
$document = $(document),
_windowSize = $(window).outerHeight();
$.fn.extend({
fnElementVisible: function(_value){ //_value = the position in % when the elem should has an opacity=1
$self = $(this),
$selfOffset = $self.offset(),
_selfHeight = $self.outerHeight();
$document.on('scroll', function(){
if($selfOffset.top - _windowSize <= $document.scrollTop() && $selfOffset.top + _selfHeight >= $document.scrollTop()){ //check if element is in the visible area of the window
$self.css({
background: 'rgba(0,0,0,' + (($document.scrollTop()-($selfOffset.top-_windowSize))/(_windowSize*(_value/100)))+ ')'
})
}
})
}
})
$('#item-1').fnElementVisible(60); //ignored
$('#item-2').fnElementVisible(70); //ignored
$('#item-3').fnElementVisible(80); //ignored
$('#item-4').fnElementVisible(90); //ignored
$('#item-5').fnElementVisible(100);
})
/*unimportant*/
body{
margin: 0;
}
.spacer{
height: 430px;
width: 100%;
background-color: lightgray;
}
.item{
background-color: blue;
color: #fff;
float: left;
display: inline-block;
width: 18%;
margin-right: 2%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="spacer">spacer</div>
<p id="item-1" class="item">elem1</p>
<p id="item-2" class="item">elem2</p>
<p id="item-3" class="item">elem3</p>
<p id="item-4" class="item">elem4</p>
<p id="item-5" class="item">elem5</p>
<div class="spacer">spacer</div>
</div>
答案 0 :(得分:0)
编写时使用的是未声明的变量
$self = $(this),
$selfOffset = $self.offset(),
_selfHeight = $self.outerHeight();
这些变量是全局变量,不在函数范围内。这引起观察到的效果。因此,您只需在变量前添加let
或var
声明,即:
let $self = $(this),
$selfOffset = $self.offset(),
_selfHeight = $self.outerHeight();