javascript - 编写简单的 JQuery 插件

标签 javascript jquery jquery-plugins

大家好,我是 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); 重复两次。有没有办法一次性写完?

非常感谢您花费宝贵的时间来解决我的问题。

感谢您的帮助!

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

关于javascript - 编写简单的 JQuery 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48166168/

相关文章:

javascript - 将来自innerjoin的数据存储在javascript数组上

jquery - jQuery 范围 slider 插件的建议

javascript - 如何使我的应用程序 url 仅在 chrome 上运行

javascript - 如何使用链接更改 Css 编码

javascript - 如何在日期选择器中将日期格式 (MM/DD/YY) 更改为 (YYYY-MM-DD)

jquery - 使用 jquery 提交表单时 Node.js 挂起

javascript - 为什么使用 $.data 而不是将属性分配给 "this"?

javascript - 避免雪花中存储过程的重复

javascript - 增加Target Box并从jquery-sortable获取Image信息

javascript - 将文本文件读取到数组