JS特效:鼠标左键弹出社会主义核心价值观
- A
访客在网站上点击屏幕的时候,会弹出“富强、民主、和谐...”文字特效,下面就给大家分享JS代码,三种方法实现:
原生JS:
window.onload = () = >{
let i = 0;
let body = document.getElementsByTagName("body")[0];
body.onclick = function(e) {
const a = ["富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善"];
let span = document.createElement("span");
span.innerText = a[(i++) % a.length];
let x = e.pageX;
let y = e.pageY;
span.style.cssText = "z-index:999999999999999999999999;top:" + (y - 20) + "px;left:" + x + "px;position:absolute;font-weight:bold;color:#ff6651;";
body.appendChild(span);
animate(span, {
"top": y - 180,
"opacity": 0
},
15, 0.01,
function() {
body.removeChild(span)
})
}
function animate(obj, json, interval, sp, fn) {
clearInterval(obj.timer);
function getStyle(obj, arr) {
if (obj.currentStyle) {
return obj.currentStyle[arr]
} else {
return document.defaultView.getComputedStyle(obj, null)[arr].replace(/px/g, "")
}
}
obj.timer = setInterval(function() {
var flag = true;
for (var arr in json) {
var icur = 0;
if (arr == "opacity") {
icur = Math.round(parseFloat(getStyle(obj, arr)) * 100)
} else {
icur = parseInt(getStyle(obj, arr))
}
var speed = (json[arr] - icur) * sp;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (icur != json[arr]) {
flag = false
}
if (arr == "opacity") {
obj.style.filter = "alpha(opacity : '+(icur + speed)+' )";
obj.style.opacity = (icur + speed) / 100
} else {
obj.style[arr] = icur + speed + "px"
}
}
if (flag) {
clearInterval(obj.timer);
if (fn) {
fn()
}
}
},
interval)
}
}
jQuery:
var a_idx = 0;
jQuery(document).ready(function($) {
$("body").click(function(e) {
var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善");
var $i = $("<span />").text(a[a_idx]);
a_idx = (a_idx + 1) % a.length;
var x = e.pageX,
y = e.pageY;
$i.css({
"z-index": 999999999999999999999999,
"top": y - 20,
"left": x,
"position": "absolute",
"font-weight": "bold",
"color": "#ff6651"
});
$("body").append($i);
$i.animate({
"top": y - 180,
"opacity": 0
},
1500,
function() {
$i.remove()
})
})
});
另一种jQuery思路:
jQuery(document).ready(function($) {
let i = 0;
$("body").click(function(e) {
let a = ["富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善"];
let $i = $("<span/>").text(a[(i++) % a.length]);
let x = e.pageX;
let y = e.pageY;
$i.css({
"z-index": 999999999999999999999999,
"top": y - 20,
"left": x,
"position": "absolute",
"font-weight": "bold",
"color": "#ff6651"
});
$("body").append($i);
$i.animate({
"top": y - 180,
"opacity": 0
},
1500, () = >{
$i.remove()
})
})
});