[英]Writing simple JQuery plugin
大家好,我是JQuery新手,所以我想知道是否可以避免代码重复。 我在这里有一个非常简单的插件:
$.fn.preview = function() {
$(this).on("click", function() {
$("body").append("<div class='c'><img></div>");
$(".c img").css("max-height", $(window).height() - 20);
$(".c img").css("max-width", $(window).width() - 20);
$(".c img").attr("src", $(this).attr("src"));
$(".c").css("display", "flex");
$(window).on("click resize", function(e) {
if ($(e.target).is(".c")) {
$(".c").remove();
}
$(".c img").css({
"max-height": $(window).height() - 20,
"max-width": $(window).width() - 20
});
});
});
}
$("img").preview();
但是这里的代码$(".c img").css("max-height",$(window).height()-20); $(".c img").css("max-width",$(window).width()-20);
$(".c img").css("max-height",$(window).height()-20); $(".c img").css("max-width",$(window).width()-20);
重复两次。 有什么办法可以写一次?
非常感谢您花费宝贵的时间处理我的问题。
感谢您的任何帮助!
$.fn.preview=function(){ $(this).on("click",function(){ $("body").append("<div class='c'><img></div>"); $(".c img").css("max-height",$(window).height()-20); $(".c img").css("max-width",$(window).width()-20); $(".c img").attr("src",$(this).attr("src")); $(".c").css("display","flex"); $(window).on("click resize",function(e){ if($(e.target).is(".c")){ $(".c").remove(); } $(".c img").css({"max-height":$(window).height()-20,"max-width":$(window).width()-20}); }); }); } $("img").preview();
.c{display:none;justify-content:center;align-items:center;position:fixed;left:0;top:0;width:100%;height:100%;background-color:rgba(0,0,0,.8)}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="https://wallpaperbrowse.com/media/images/Wallpaper-4K.jpg" width="200"/>
您可以通过将一个对象作为.css()
函数参数来声明多个CSS规则:
$(".c img").css({
"max-height": $(window).height()-20,
"max-width": $(window).width()-20
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.