萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 發光漸隱文字特效實作

效果簡介

利用 IE 專屬 filter: glow() 濾鏡,實現文字發光→漸隱→切換訊息的循環動畫。注意:此為舊版 IE 專用技術,現代瀏覽器建議改用 CSS3 text-shadow + @keyframes 實現跨瀏覽器相容效果。

實作步驟

步驟 1:HEAD 區塊引入腳本

<script language="JavaScript">
<!--
var thisSize = 20;
var textFont = "隸書";

var textColor = [
    "000000","000000","000000","111111","222222","333333","444444","555555",
    "666666","777777","888888","999999","aaaaaa","bbbbbb","cccccc","dddddd",
    "eeeeee","ffffff","ffffff"
];

var message = [
    "歡迎光臨三聯素材",
    "請多停留一會",
    "你會有更多的收獲",
    "請再次光臨"
];
var i_message = 0;
var i_strength = 0;
var timer;

function glowText() {
    if (document.all) {
        if (i_strength <= 17) {
            glowdiv.innerText = message[i_message];
            document.all.glowdiv.style.filter = "glow(color=" + textColor[i_strength] + ", strength=4)";
            i_strength++;
            timer = setTimeout("glowText()", 100);
        } else {
            clearTimeout(timer);
            setTimeout("deGlowText()", 1500);
        }
    }
}

function deGlowText() {
    if (document.all) {
        if (i_strength >= 0) {
            glowdiv.innerText = message[i_message];
            document.all.glowdiv.style.filter = "glow(color=" + textColor[i_strength] + ", strength=4)";
            i_strength--;
            timer = setTimeout("deGlowText()", 100);
        } else {
            clearTimeout(timer);
            i_message++;
            if (i_message >= message.length) i_message = 0;
            i_strength = 0;
            intermezzo();
        }
    }
}

function intermezzo() {
    glowdiv.innerText = "";
    setTimeout("glowText()", 1000);
}
// -->
</script>

步驟 2:BODY 區放置顯示容器

<div id="glowdiv" style="position:absolute; visibility:visible; width:600px;
     text-align:center; top:185px; left:70px; font-family:隸書; font-size:30pt; color:#000000">
</div>

步驟 3:啟動動畫

<body bgcolor="#fef4d9" onLoad="glowText()">

現代化替代方案(CSS3)

@keyframes glowFade {
    0%   { text-shadow: 0 0 4px #000; opacity: 1; }
    50%  { text-shadow: 0 0 20px #fff; opacity: 1; }
    100% { text-shadow: 0 0 4px #000; opacity: 0; }
}

.glow-text {
    animation: glowFade 3s infinite;
    font-family: "標楷體", cursive;
    font-size: 2rem;
    color: #000;
}

CSS3 方案支援所有現代瀏覽器(Chrome、Firefox、Edge、Safari),且效能更佳、維護更簡單。

copyright © 萬盛學電腦網 all rights reserved