javascript代码中,应合理出现注释,标注代码的用意,增加代码的可读性,方便代码维护和修改。
反例
function fixedHeader() {
var self = this,
$root = $(self.$el),
$ctRoot = $root.find('#ct-root'),
$ctHeader = $root.find('.scroll-header'),
ctHeaderH = parseInt(window.getComputedStyle($ctHeader[0]).height),
maxOpactiyH = parseInt(ctHeaderH * 2),
opacity = 0;
$ctRoot.on('scroll', function() {
var $this = $(this),
scrollcur = $this.scrollTop();
if (scrollcur > 0) {
$ctHeader.removeClass('hide');
if(scrollcur < maxOpactiyH){
opacity = scrollcur/maxOpactiyH;
}if(scrollcur > maxOpactiyH){
opacity = 1;
}
$ctHeader.css('opacity', opacity);
}else{
$ctHeader.addClass('hide');
$ctHeader.css('opacity', 0);
}
});
}
正例
function fixedHeader() {
var self = this,
$root = $(self.$el),
$ctRoot = $root.find('#ct-root'),
$ctHeader = $root.find('.scroll-header'),
ctHeaderH = parseInt(window.getComputedStyle($ctHeader[0]).height),//头部高度
maxOpactiyH = parseInt(ctHeaderH * 2),//滚动区间设在头部高度1.5倍
opacity = 0;
$ctRoot.on('scroll', function() {
var $this = $(this),
scrollcur = $this.scrollTop();
//将导航条定位到顶部
if (scrollcur > 0) {
$ctHeader.removeClass('hide');
//滚动1.5倍自身高度内,透明度变化
if(scrollcur < maxOpactiyH){
opacity = scrollcur/maxOpactiyH;
}if(scrollcur > maxOpactiyH){//规避卡顿造成的影响
opacity = 1;
}
$ctHeader.css('opacity', opacity);
}else{
$ctHeader.addClass('hide');
$ctHeader.css('opacity', 0);
}
});
}