如何重用jQuery中的自定义函数来应用多个css属性

How do I reuse a custom function in jQuery to apply multiple css properties?

本文关键字:应用 css 属性 自定义函数 何重用 jQuery      更新时间:2023-09-26

超级简单的概念,但它给我带来了麻烦。。。

共5个div元素第一个div居中,z索引到前面。其他4个div各占页面的1/4。悬停时,每个分区都将一个唯一的css属性应用于第一分区。

以下是我目前拥有的

或者这是代码:

$(document).ready(function(){
  function point(a, b, c, d) {
    $(".middle").css("transition", ".15s ease-in-out all");
    $(".middle").css("border-radius", a . "% " . b . "% " . c . "% " . d . "%");
  }
  function unpoint() {
    $(".middle").css("transition", ".15s ease-in-out all");
    $(".middle").css("border-radius", "50% 50% 50% 50%");
  }
  $(".section-1")
    .on( "mouseenter", point(0, 50, 50, 50) )
    .on( "mouseleave", unpoint() );
});

谢谢你的帮助!

您可以制作一个小插件

(function($) {
  function mouseenter(a, b, c, d) {
    $(".middle", this).css({
      transition: ".15s ease-in-out all",
      borderRadius: [a, b, c, d].map(function(side) { return side+"%"; }).join(" ");
    });
  }
  function mouseleave() {
    $(".middle", this).css({
      transition: ".15s ease-in-out all",
      borderRadius: "50%"
    });
  }
  $.fn.point = function(a, b, c, d) {
    return this.each(function(idx, elem)) {
      $(elem).hover(
        function() { mouseenter.call(this, a, b, c, d); },
        function() { mouseleave.call(this); }
      );
    });
  };
})(jQuery);

然后你可以像这个一样使用它

$(document).ready(function() {
  $(".section-1").point(0, 50, 50, 50);
});

在我的第一个视图中,我发现您的代码有一些问题。。

第一个问题:给定的行中存在语法错误。它应该是+代替。(点)

$(".middle").css("border-radius", a + "% " + b + "% " + c + "% " + d + "%");

第二个问题:您没有将函数分配给回调,但您只是在调用该函数。正确的语法应该是。。

$(".section-1")
    .on( "mouseenter", point )
    .on( "mouseleave", unpoint );