1. 程式人生 > >AngularJS 指令 實現文本水平滾動效果

AngularJS 指令 實現文本水平滾動效果

inner 滾動效果 dom對象 定時任務 oot 水平 ack -i .org

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <script src="https://cdn.bootcss.com/angular.js/1.6.7/angular.min.js"
></script> <script src="http://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script> <style> .transverseRoll { white-space: nowrap; overflow: hidden; width
: 90%; margin: 3px auto; padding: 10px 20px 15px 0px; position: fixed; left: 5%; color: white; background-color: black; z-index: 1; } </style> <script> var app = angular.module("myApp", []); app.directive(
"transverseRolling", function() { return { link: function(scope, element, attrs) { //定義一個定時任務對象,用於鼠標懸停時取消滾動效果 var event; function scroll(obj) { //獲取滾動條到元素左邊的距離 var tmp = (obj.scrollLeft) ++; if (obj.scrollLeft == tmp) { //當滾動條到達右邊頂端時,將文字追加在元素末尾 obj.innerHTML += "&nbsp&nbsp&nbsp&nbsp" + obj.innerHTML; } if (obj.scrollLeft >= obj.firstChild.offsetWidth) { //當滾動條滾動了初始內容的寬度時滾動條回到最左端 obj.scrollLeft = 0; } } function mouseover() { //鼠標移入時取消滾動效果 clearInterval(event); } function _scroll(param) { //將滾動條位置向右移動一個像素,計算滾動條是否到達右側盡頭 return function() { scroll(param); }; } function _mouseout(target) { //鼠標移出事件,設置滾動效果 return function() { if (target) { event = setInterval(_scroll(target), 100); } }; } //將DOM對象轉換為Jquery對象 var $target = $(element[0]); // 設置滾動效果 event = setInterval(_scroll(element[0]), 100); //給指令所在的div添加鼠標移入移出事件監聽 element[0].addEventListener("mouseover", mouseover); element[0].addEventListener("mouseout", _mouseout(element[0])); } } }); </script> </head> <body ng-app="myApp"> <div class="transverseRoll" transverse-rolling>恨臺上卿卿或臺下我我,不是我跟你。俗塵渺渺天意茫茫,將你共我分開。斷腸字點點風雨聲連連,似是故人來。</div> </body> </html>

AngularJS 指令 實現文本水平滾動效果