在jquery中创建循环

时间:2017-12-18 19:49:24

标签: javascript jquery arrays loops

当我点击刷新按钮时,我正在尝试构建一个更改背景(颜色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>

5 个答案:

答案 0 :(得分:3)

我认为你不需要循环。请尝试下面的代码。但是我会建议你制作单独的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);
    });
        }
}); 

答案 1 :(得分:1)

编辑我的示例以使用您的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>

添加了评论,使其更容易理解。

答案 2 :(得分:1)

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

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

现在您可以收听事件并相应地调用“更改”功能。

答案 3 :(得分:1)

所以我会通过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>

答案 4 :(得分:1)

JQuery Animate来自他们的文档

动画属性和值

除非如下所述,否则应将所有动画属性设置为单个数值。大多数非数字属性无法使用基本jQuery功能进行动画处理(例如,宽度,高度或左边可以设置动画,但背景颜色不能,除非使用jQuery.Color插件) 。除非另有说明,否则属性值被视为多个像素。可以在适用的情况下指定单位em和%。

我的Html和JavaScript

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;