【问题标题】:creating loop in jquery在 jquery 中创建循环
【发布时间】:2017-12-18 19:49:23
【问题描述】:

我正在尝试构建一个在用户单击刷新按钮时更改背景(颜色 a)、框(颜色 b)和文本颜色(颜色 a)的函数。我已经设置了颜色数组,但无法弄清楚如何正确循环数组。有人可以帮忙吗?

var colors = [
["#808080", "#f08080"],
["#2f4f4f", "#cdcdc1"],
["#F3E4C3", "#191970"],
["#DD5C3D", "#495496"],
["#ffbdbd", "#bdffff"],
["#c9c9ff", "#282833"],
["#fff5ee", "#4682b4"]]

我想我可以在下面做这样的事情:

     $("#refresh").click(function(){
        $("box").animate({
            backgroundColor: colors[0][1],
        }, 500);
        $("box").css("color", colors[0][0]);
        $("background").animate({
            backgroundColor: colors[0][0],
        }, 500);
        //add something that triggers loop here
        });

下面是我的html:

<body>
<section id="main" class="box" style="margin-bottom: 10px">
    <div id="city"></div>
    <div id="detail"></div>
    <div id="icon"></div>
    <div id="temperature"></div>
    <div id="fcicon" class="inrow">
        <div id="f">F</div><div style="opacity: 0.5">/</div><div id="c">C</div>
    </div>
    <div id="refresh"><i class="fa fa-refresh"></i></div>
</section>

【问题讨论】:

  • 你的 HTML 是什么样的?
  • @Snowmonkey 刚刚添加了它-谢谢!
  • 因此,您正在为 HTML 中不存在的三个 DOM 元素制作动画——一个框元素、一个部分元素和一个背景元素。是的,他们不会那样制作动画。
  • 循环有什么作用?或者你的意思是每次他们点击刷新时你选择数组中的下一个颜色?这个问题不清楚。
  • 嗨@ErikPhilips,是的,这就是我想要弄清楚的。刷新按钮应该指向数组中的下一个颜色对。

标签: javascript jquery arrays loops


【解决方案1】:

我认为您不需要循环。试试下面的代码。但是,我建议您制作单独的 css 类并在它们之间切换。

var colors = [["#808080", "#f08080"],
              ["#2f4f4f", "#cdcdc1"],
              ["#F3E4C3", "#191970"],
              ["#DD5C3D", "#495496"],
              ["#ffbdbd", "#bdffff"],
              ["#c9c9ff", "#282833"],
              ["#fff5ee", "#4682b4"]];

$(document).on(function(){
    var i=0;
    $("#refresh").click(function(){
        if(colors.length==i+1){
            i=0;
        }else{
            i=i+1;
            $("box").animate({
                backgroundColor: colors[i][1],
            }, 500);
            $("section").animate({
                backgroundColor: colors[i][0],
            }, 500);
            $("background").animate({
                backgroundColor: colors[i][0],
            }, 500);
    });
        }
}); 

【讨论】:

  • 啊这绝对是一个简单易行的解决方案!
【解决方案2】:

编辑了我的示例以使用您的 HTML,效果很好。我将类从 .container 更改为 .box,因为这就是您正在使用的。

这里是as a fiddle,以防万一。

// Array of color pairs that we'll use for background
//  colors, text colors and border colors.
var colors = [
  ["#808080", "#f08080"],
  ["#2f4f4f", "#cdcdc1"],
  ["#F3E4C3", "#191970"],
  ["#DD5C3D", "#495496"],
  ["#ffbdbd", "#bdffff"],
  ["#c9c9ff", "#282833"],
  ["#fff5ee", "#4682b4"]
];

// The counter refers to which pair in the array we're
//   currently referencing.
var counter = 0;

// When the refresh div gets clicked, 
$("#refresh").click(function() {
  // check the counter and increment or reset it.
  if (counter >= colors.length - 1) {
    counter = 0;
  } else {
    counter++
  }
  // Now, we want to animate CSS attributes on the
  //  container object. We'll use the color pair 
  //  we're currently pointing to for the background
  //  text and border colors.
  $(".box").animate({
    backgroundColor: colors[counter][1],
    color: colors[counter][0],
    borderColor: colors[counter][0]
  }, 500);
});
.box {
  position: relative;
  border: 1px solid blue;
  height: 200px;
  width: 200px;
}
.box #city {
  font-weight: bolder;
  font-size: 14px;
}
#refresh {
  position: absolute;
  bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<section id="main" class="box" style="margin-bottom: 10px">
    <div id="city">Worcester, MA</div>
    <div id="detail"></div>
    <div id="icon"></div>
    <div id="temperature"></div>
    <div id="fcicon" class="inrow">
        <div id="f">F</div><div style="opacity: 0.5">/</div><div id="c">C</div>
    </div>
    <div id="refresh"><i class="fa fa-refresh"></i></div>
</section>

添加了 cmets 使其更容易理解。

【讨论】:

  • 非常感谢每一行的详细分解!
  • 我发现,如果我至少在原型设计期间没有彻底评论我的代码,我会破坏一些东西并且不明白为什么。很高兴它有帮助。
【解决方案3】:

您可以通过创建闭包来简单地跟踪索引。

function looper(){
    let i = 0;
    return function(){
       $("box").animate({
        backgroundColor: colors[i][1],
       }, 500);
       $("section").animate({
        backgroundColor: colors[i][0],
       }, 500);
       $("background").animate({
        backgroundColor: colors[i][0],
       }, 500);

       i++;
       if(i === colors.length){
          i = 0;
        }
   }
}

let change = looper();

现在您可以监听事件并相应地调用函数“change”。

【讨论】:

    【解决方案4】:

    所以我会通过data() 将值存储在元素中。使它非常容易和可重复使用。花点时间阅读Decoupling Your HTML, CSS, and JavaScript

    以下代码是可重用和可扩展的。通过允许多个按钮具有不同的目标来刷新可重用。通过允许您根据需要向动画添加任意数量的项目来进行扩展。老实说,我只是将颜色放在js-refresh 按钮中,这样每个刷新按钮都可以拥有自己的数组。

    $(document).ready(()=>{
      var colors = [
        ["#808080", "#f08080"],
        ["#2f4f4f", "#cdcdc1"],
        ["#F3E4C3", "#191970"],
        ["#DD5C3D", "#495496"],
        ["#ffbdbd", "#bdffff"],
        ["#c9c9ff", "#282833"],
        ["#fff5ee", "#4682b4"]];
    
      $(".js-refresh").on('click', (e) => {
        var $this = $(e.currentTarget);
        var selector = $this.data('refresh-target');
        $(selector).each((i,e)=>{
          var $this = $(e);
          var idx = $this.data('js-refresh-index') || 1;
          idx = idx >= colors.length ? 1 : idx + 1;
          $this
            .data('js-refresh-index', idx)
            .stop()
            .animate({
              backgroundColor: colors[idx-1][0],
            }, 1)
            .animate({
              backgroundColor: colors[idx-1][1],
            }, 500);
        })
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script
      src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"
      integrity="sha256-H28SdxWrZ387Ldn0qogCzFiUDDxfPiNIyJX7BECQkDE="
      crossorigin="anonymous"></script>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
    <section id="main" class="box" style="margin-bottom: 10px">
        <div id="city"></div>
        <div id="detail"></div>
        <div id="icon"></div>
        <div id="temperature" class="refresh-1">Temp</div>
        <div id="fcicon" class="inrow">
            <div id="f">F</div><div style="opacity: 0.5">/</div><div id="c">C</div>
        </div>
        <div class="js-refresh" data-refresh-target=".refresh-1">
          <i class="fa fa-refresh"></i>
        </div>
        </section>

    【讨论】:

    • 哇哦!这对我来说是一个非常先进的解决方案哈哈。我一定会阅读您与我分享的文章。非常感谢埃里克!!
    【解决方案5】:

    JQuery Animate 来自他们的文档

    动画属性和值

    所有动画属性都应动画为单个数值,除非以下说明;大多数非数字属性无法使用基本的 jQuery 功能进行动画处理(例如,宽度、高度或左侧可以进行动画处理,但 background-color 不能,除非使用了 jQuery.Color 插件) .除非另有说明,否则属性值被视为像素数。如果适用,可以指定单位 em 和 %。

    我的 HTML 和 JavaScript

    <!DOCTYPE html>
    <html>
    <head>
        <title>Animate</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
        <div class="row">
            <select id="colors">
                <option value="BlueWhite">Background: Blue, Color: White</option>
                <option value="YellowBlue">Background: Yellow, Color: Blue</option>
                <option value="WhiteRed">Background: White, Color: Red</option>
                <option value="BlackWhite">Background: Black, Color: White</option>
            </select>
            <div id="main" class="box" style="margin-bottom: 10px">
                <div id="city"></div>
                <div id="detail"></div>
                <div id="icon"></div>
                <div id="temperature"></div>
                <div id="fcicon" class="inrow">
                    <div id="f">F</div><div style="opacity: 0.5">/</div><div id="c">C</div>
                </div>
            </div>
            <button id="refresh" class="btn btn-primary"><i class="fa fa-refresh"></i></button>
        </div>
        <script>
            $(document).ready(function () {
                var colors = {
                    "BlueWhite": {
                        "Background": "#0000ff",
                        "Color": "#ffffff"
                    },
                    "YellowBlue": {
                        "Background": "#FFFF00",
                        "Color": "#0000ff"
                    },
                    "WhiteRed": {
                        "Background": "#ffffff",
                        "Color": "#ff0000"
                    },
                    "BlackWhite": {
                        "Background": "#000000",
                        "Color": "#ffffff"
                    }
                };
                $("#refresh").click(function () {
                    var selected = $("#colors").val();
                    var colorObj;
                    if(colors[selected] != undefined) {
                      colorObj = colors[selected];
                    } else {
                      colorObj = colors["BlackWhite"];
                    }
                    $("#main").animate({
                        backgroundColor: colorObj.Background,
                        color: colorObj.Color
                    }, function () {
                        $(this).css("backgroundColor", colorObj.Background).css("color", colorObj.Color);
                    });
                });
            });
        </script>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 2023-03-11
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多