【问题标题】:Randomize border color on hover悬停时随机化边框颜色
【发布时间】:2016-09-19 12:23:57
【问题描述】:

我有这个脚本可以在悬停时随机化我的边框 img 的颜色,但是当我离开 img 时它也会删除我的基本边框..(从一开始我的所有 img 都有一个灰色边框,我想要这个边框永远留在那里不被移除)

script>      
$(function() {
  var colors = ["#FC3E6B","#24FF00","#0087F9","#F9F900"];

  $('.grid-item-content').hover(
    function() {
      var rand = Math.floor(Math.random()*colors.length);

      $(this).css('border-style', 'solid');
      $(this).css('border-width', '10px');
      $(this).css('border-color', colors[rand]);
    },
    function() {
      $(this).css('border-style', 'none');
    }
  );
});
</script>

【问题讨论】:

    标签: javascript jquery random colors border


    【解决方案1】:

    您好,您可以通过删除内联样式属性轻松做到这一点

    $(function() {
      var colors = ["#FC3E6B","#24FF00","#0087F9","#F9F900"];
    
      $('.grid-item-content').hover(
        function() {
          var rand = Math.floor(Math.random()*colors.length);
          $(this).css('border-style', 'solid');
          $(this).css('border-width', '1px');
          $(this).css('border-color', colors[rand]);
        },
        function () {
            $(this).removeAttr('style');
        }
      );
    });
    

    工作小提琴:https://jsfiddle.net/jdro6qch/

    【讨论】:

      【解决方案2】:

      你只需要修改第二个函数来设置边框灰色。

      <script>      
      $(function() {
        var colors = ["#FC3E6B","#24FF00","#0087F9","#F9F900"];
      
        $('.grid-item-content').hover(
          function() {
            var rand = Math.floor(Math.random()*colors.length);
      
            $(this).css('border-style', 'solid');
            $(this).css('border-width', '10px');
            $(this).css('border-color', colors[rand]);
          },
          function() {
            $(this).css('border-style', 'solid');
            $(this).css('border-width', '10px');
            $(this).css('border-color', 'grey');
          }
        );
      });
      </script>
      

      【讨论】:

      • 完美的感谢队友!
      猜你喜欢
      • 2012-03-15
      • 2021-10-18
      • 1970-01-01
      • 2020-01-28
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      相关资源
      最近更新 更多