javascript代码中,应合理出现注释,标注代码的用意,增加代码的可读性,方便代码维护和修改。

    反例

    1. function fixedHeader() {
    2. var self = this,
    3. $root = $(self.$el),
    4. $ctRoot = $root.find('#ct-root'),
    5. $ctHeader = $root.find('.scroll-header'),
    6. ctHeaderH = parseInt(window.getComputedStyle($ctHeader[0]).height),
    7. maxOpactiyH = parseInt(ctHeaderH * 2),
    8. opacity = 0;
    9. $ctRoot.on('scroll', function() {
    10. var $this = $(this),
    11. scrollcur = $this.scrollTop();
    12. if (scrollcur > 0) {
    13. $ctHeader.removeClass('hide');
    14. if(scrollcur < maxOpactiyH){
    15. opacity = scrollcur/maxOpactiyH;
    16. }if(scrollcur > maxOpactiyH){
    17. opacity = 1;
    18. }
    19. $ctHeader.css('opacity', opacity);
    20. }else{
    21. $ctHeader.addClass('hide');
    22. $ctHeader.css('opacity', 0);
    23. }
    24. });
    25. }

    正例

    1. function fixedHeader() {
    2. var self = this,
    3. $root = $(self.$el),
    4. $ctRoot = $root.find('#ct-root'),
    5. $ctHeader = $root.find('.scroll-header'),
    6. ctHeaderH = parseInt(window.getComputedStyle($ctHeader[0]).height),//头部高度
    7. maxOpactiyH = parseInt(ctHeaderH * 2),//滚动区间设在头部高度1.5倍
    8. opacity = 0;
    9. $ctRoot.on('scroll', function() {
    10. var $this = $(this),
    11. scrollcur = $this.scrollTop();
    12. //将导航条定位到顶部
    13. if (scrollcur > 0) {
    14. $ctHeader.removeClass('hide');
    15. //滚动1.5倍自身高度内,透明度变化
    16. if(scrollcur < maxOpactiyH){
    17. opacity = scrollcur/maxOpactiyH;
    18. }if(scrollcur > maxOpactiyH){//规避卡顿造成的影响
    19. opacity = 1;
    20. }
    21. $ctHeader.css('opacity', opacity);
    22. }else{
    23. $ctHeader.addClass('hide');
    24. $ctHeader.css('opacity', 0);
    25. }
    26. });
    27. }