[英]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.