如果你编写web应用程序,你几乎肯定会使用jQuery。构建一个响应式网站或应用程序,jQuery可以有很大的帮助。事实上,它可以将整个用户体验提升到一个新的水平。在本文中,我编写了我最喜欢的jQuery提示和技巧来制作和增强响应式网站
滚动到某个元素
无尽的滚动并不是interesting的事情。这就是为什么设置scrolls的作用,因为你的访客不需要花费10分钟才能到达他们正在寻找的信息。
我们先从自动滚动开始:下面的代码会滚动到页面上的特定元素:
$('html, body').animate({ scrollTop: $("#target").offset().top }, 1000);
现在,让我们设置一个滚动,用户将通过点击一个链接来激活:
$('a#source').on('click', function(event) { $('body').scrollTo('#target'); });
检测视窗大小
CSS媒体查询允许您检测视窗大小,并根据视口宽度将不同的CSS样式应用于元素。
这也可以在jQuery中完成,它对于你无法实现单独使用CSS的结果是非常有用。下面的示例演示如何检测viewport宽度,然后将一个元素添加到列表中。
if ($(window).width() < 960) { $( "ul.mylist").append("<li>One more list element</li>"); }
将导航菜单变为下拉菜单
当你的网站有许多菜单项时,在小屏幕上显示可能会非常棘手。因此,解决这个问题的一个简单方法是将导航转换为下拉菜单。
下面的代码:从nav中获取items ,并将其附加到select下拉列表:
// Create the dropdown base $("<select />").appendTo("nav"); // Create default option "Go to..." $("<option />", { "selected": "selected", "value" : "", "text" : "Go to..." }).appendTo("nav select"); // Populate dropdown with menu items $("nav a").each(function() { var el = $(this); $("<option />", { "value" : el.attr("href"), "text" : el.text() }).appendTo("nav select"); }); $("nav select").change(function() { window.location = $(this).find("option:selected").val(); });
将Height/Width的Animate设置为“Auto”
如果你已经尝试使用thing.animate({“height”:“auto”});在一个元素上,你已经注意到它不起作用。令人高兴的是,这个问题有一个快速而且有效的解决方案。
代码如下:
jQuery.fn.animateAuto = function(prop, speed, callback){ var elem, height, width; return this.each(function(i, el){ el = jQuery(el), elem = el.clone().css({"height":"auto","width":"auto"}).appendTo("body"); height = elem.css("height"), width = elem.css("width"), elem.remove(); if(prop === "height") el.animate({"height":height}, speed, callback); else if(prop === "width") el.animate({"width":width}, speed, callback); else if(prop === "both") el.animate({"width":width,"height":height}, speed, callback); });
以及如何使用它:
$(".animateHeight").bind("click", function(e){ $(".test").animateAuto("height", 1000); }); $(".animateWidth").bind("click", function(e){ $(".test").animateAuto("width", 1000); }); $(".animateBoth").bind("click", function(e){ $(".test").animateAuto("both", 1000); });
延迟加载图像
延迟加载是一种强制页面只加载客户端屏幕上可见的图像的技术。它已被证明是非常有效的提高您的网站加载速度,这是非常重要的用户体验和搜索引擎优化。有很多jQuery插件专门用于在您的网站上实现延迟加载。如果你使用WordPress,我绝对推荐这个。
至于jQuery的lazyload插件,我已经在几个站点上使用这个,简单的叫做Lazy Load。它的使用非常简单。第一步是将插件导入到您的HTML页面中:
<script src="https://cdn.jsdelivr.net/npm/lazyload@2.0.0-beta.2/lazyload.js"></script>
现在HTML代码:默认情况下,Lazy Load假定原始高分辨率图像的URL可以在data-src属性中找到。您还可以在src属性中包含一个可选的低分辨率占位符。
<img class="lazyload" data-src="img/example.jpg" width="765" height="574"> <img class="lazyload" src="img/example-thumb.jpg" data-src="img/example.jpg" width="765" height="574">
现在是激活延迟加载的时候了。使用HTML就可以使用factory方法初始化插件。如果你没有传递任何设置或图像元素,它会延迟加载lazyload类的所有图像。
lazyload();
确实有更多的选项可用,所以你只需看一下插件文档。
原创文章,作者:webstack,如若转载,请注明出处:https://www.webstacks.cn/tutorial/652.html