简体   繁体   English

编写简单的JQuery插件

[英]Writing simple JQuery plugin

Hello everyone I'm new to JQuery so I wanted to know if I can avoid repeats in my code. 大家好,我是JQuery新手,所以我想知道是否可以避免代码重复。 I have a very simple plugin here : 我在这里有一个非常简单的插件:

  $.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();

But here the code $(".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); $(".c img").css("max-height",$(window).height()-20); $(".c img").css("max-width",$(window).width()-20); repeats two times. 重复两次。 Is there any way to write it once? 有什么办法可以写一次?

Thank you very much for spending your precious time with my issue. 非常感谢您花费宝贵的时间处理我的问题。

Thank you for any help! 感谢您的任何帮助!

 $.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"/> 

You can declare multiple CSS rules by passing an object as the .css() function parameter: 您可以通过将一个对象作为.css()函数参数来声明多个CSS规则:

$(".c img").css({
    "max-height": $(window).height()-20,
    "max-width": $(window).width()-20
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM