--- tags: jQuery, js --- # jQuery 常用指令 ###### tags: `jQuery`, `js` ## 阻止元素發生默認的行為 ```python=1 $("a").click(function(event){ event.preventDefault(); }); ``` ## 若有 選擇元素 則執行程式碼 ```python=1 if ($('.class').length > 0) {  程式碼 } ``` ## 增加移除Class ```python=1 $('.btn').on('hover', function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); }); ``` ```python=1 $('.btn').on('hover', function () { $(this).toggleClass('hover'); }); ``` ## 增加Class 移除同層Class ```python=1 $('.menu li').on('click', function(){ if ( $(this).hasClass('active') ) { $(this).removeClass('active'); } else { $(this).siblings('.active').removeClass('active'); $(this).addClass('active'); } }); ``` ## 返回頂部按鈕 ```python=1 $('a[href^="#top"]').on('click', function(event) { event.preventDefault(); $('html, body').animate({ scrollTop: 0 }, 1000); }); ``` ```python=1 var btn = $('#bttop'); btn.on('click', function (e) { e.preventDefault(); $('html, body').animate({ scrollTop: 0 }, '300'); }); ``` ```python=1 <div class="container"> <a href="#" id="gotop">Back to top</a> </div> $('.container').on('click', '#gotop', function (e) { e.preventDefault(); $('html, body').animate({scrollTop: 0}, 800); }); ``` ## 平滑滾動到ID ```python=1 $('a[href*="#"]').on('click', function (e) {   e.preventDefault();   $('html, body').animate({     scrollTop: $($(this).attr('href')).offset().top   }, 500, 'linear'); }); ``` ## 平滑滾動到 Header相對位置 ```python=1 $('.taget').on('click', function() { var headerHeight = $('#header').height(); var thisclick = $(this); var thebody = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'), thebodyscrollTop = thebody.scrollTop(); thebody.stop().animate({ scrollTop: thebodyscrollTop }, { duration: 500, easing: 'linear', step: function(now, fx) { fx.end = thisclick.offset().top - headerHeight; }, }); }); ``` jQuery – 在IE中使用 $(“body”) 捲動畫面無法運作的解決辦法 在IE11以前的都有這個問題。只要在你的程式碼改用這樣就可以: var $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'); $body.animate({ scrollTop: val }, 500);