$(function() { var windowWidth = $(window).width() + getScrollbarWidth(); // 窗口宽度 /********************************************************************* 导航 */ // 点击箭头展开下拉菜单 $(".nav-li").click(function (event) { if ($(event.target).attr('id') === 'arrows') { let list = $(this).find(".nav-hide-list"); let arrowhead = $(this).find("#arrows"); if(arrowhead.attr('data-open') === 'true') { list.stop().animate({ height: 0 }, 100); arrowhead.css({ 'transform': 'rotate(0deg)' }) arrowhead.attr('data-open', 'false'); } else { let autoHeight = list.css('height', 'auto').height(); list.height(0).stop().animate({ height: autoHeight }, 100); arrowhead.css({ 'transform': 'rotate(90deg)' }) arrowhead.attr('data-open', 'true'); } $(this).siblings(".nav-li").each(function (index, item) { let openList = $(item).find(".nav-hide-list"); let openArrowhead = $(item).find("#arrows"); openArrowhead.css({ 'transform': 'rotate(0deg)' }) openArrowhead.attr('data-open', 'false'); openList.stop().animate({ height: 0 }, 100); }) } }) // 根据窗口宽度,改变导航栏事件 function headResize() { if (windowWidth < 1200) { $(".nav-li").unbind('mouseenter mouseleave'); // 移除鼠标划过事件 } else { $(".nav-li").unbind('mouseenter mouseleave');// 移除鼠标划过事件 // 添加鼠标划过事件 $(".nav-li") .mouseenter(function() { let list = $(this).find(".nav-hide-list"); let autoHeight = list.css('height', 'auto').height(); list.height(0).stop().animate({ height: autoHeight }, 100); }) .mouseleave(function() { let list = $(this).find(".nav-hide-list"); list.stop().animate({ height: 0 }, 100); }) } } headResize() // 浏览器窗口大小变化时 $(window).resize(function() { windowWidth = $(window).width() + getScrollbarWidth(); headResize() if (windowWidth < 1200) { $(".nav-li").each(function (index, item) { let list = $(item).find(".nav-hide-list"); let arrowhead = $(item).find("#arrows"); arrowhead.css({ 'transform': 'rotate(0deg)' }) arrowhead.attr('data-open', 'false'); list.stop().animate({ height: 0 }, 100); }) } }) /********************************************************************* 回到顶部 */ $('#goTop').on('click', function() { $('html, body').animate({ scrollTop: 0 }, 100); }) }) // 获取滚动条宽度 function getScrollbarWidth() { var odiv = document.createElement('div'),//创建一个div styles = { width: '100px', height: '100px', overflowY: 'scroll'//让他有滚动条 }, i, scrollbarWidth; for (i in styles) odiv.style[i] = styles[i]; document.body.appendChild(odiv);//把div添加到body中 scrollbarWidth = odiv.offsetWidth - odiv.clientWidth;//相减 odiv.remove();//移除创建的div return scrollbarWidth;//返回滚动条宽度 }