gpt4 book ai didi

javascript - AngularJS:如何使这个自动收报机动画连续并动态获取元素尺寸

转载 作者:行者123 更新时间:2023-11-28 17:46:07 26 4
gpt4 key购买 nike

这是我第一次尝试 AngularJS,我正在构建一个盒子的自动收报机

CodePen Here

代码:

index.jade:

doctype html
html(ng-app="ticker")
head
script(src="../bower_components/angular/angular.js", type="text/javascript")
script(src="script.js")
link(rel="stylesheet", href="css.css")
body
div(ng-controller="tickerCtrl")

.ticker
.viewport(ng-class="{moving: moving}", ng-click="moveLeft()")
.box(ng-repeat="box in boxes")
span {{ box.title }}

button(type="button", ng-click="moveLeft()") < Move left

脚本.js

angular.module('ticker', [])
.controller('tickerCtrl', ['$scope', '$window', function($scope, $window) {
$scope.boxes = [
{title: 'Box 1'},
{title: 'Box 2'},
{title: 'Box 3'},
{title: 'Box 4'},
{title: 'Box 5'},
{title: 'Box 6'},
{title: 'Box 7'},
{title: 'Box 8'},
{title: 'Box 9'},
{title: 'Box 10'}
];
$scope.moving = false;

$scope.moveLeft = function() {
$scope.moving = true;
$window.setTimeout($scope.switchFirst, 2000);
};
$scope.switchFirst = function() {
$scope.boxes.push($scope.boxes.shift());
$scope.moving = false;
$scope.$apply();
};
}]);

css.less

.ticker {
width: 90%;
padding: 1em 1em;
height: 100px;
overflow: hidden;
position: relative;

.viewport {
&.moving {
animation: moveLeft 1 2s linear;
}

position: absolute;
height: 100px;

border-width: 1px 0;
border-style: solid;
border-color: #cccccc;

white-space: nowrap;

.box {
display: inline-block;
width: 100px;
height: 100%;

border: 1px solid #eee;
margin: 0 5px;

text-align: center;
}
}
}

@keyframes moveLeft {
0% { transform: translateX(0) }
100% { transform: translateX(-110px) }
}

我遇到了以下问题:

  • 如何使运动连续进行?当我尝试在 tickerCtrl 中添加 $window.setInterval($scope.moveLeft, 2000); 时,动画仅在第一次应用。

  • 如何动态获取元素尺寸?目前,视口(viewport)向左移动 110px,但这应该是第一个元素的 outerWidth 的值(在 jQuery 术语中)。

  • 这是否是 AngularJS 的正确应用程序,还是我应该切换到 jQuery?

最佳答案

编辑:查看我的解决方案 - http://cdpn.io/rlgve

首先,对于 Angular,不要使用 setTimeout。使用 Angular 的 $timeout。

其次,如果你想重复它,你可以使用 setInterval,或者在 Angular 中,$interval。

Angular 使用更轻量级的类似 jquery 的代码进行 dom 操作,称为 JQlite,除此之外您不需要 jQuery。您可以使用 $element 访问 DOM 元素。

或者 javascript DOM API...

document.body.getElementsByClassName('某些类')[0].clientWidth

关于javascript - AngularJS:如何使这个自动收报机动画连续并动态获取元素尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com