實現效果:
文字陰影的鼠標隨動效果
關鍵點:
1.在script標籤中,我們使用3個變量,一個指向div元素,一個指向其子元素h1,最後一個變量factor用於標記陰影距離h1中心的距離和鼠標距離h1中心距離的比例,用於計算陰影的具體位置。
2.在hero元素上監聽鼠標移動事件mousemove,並添加事件處理的回調函數shadowMove.
hero.addEventListener('mousemove',shadowMove);
3.爲獲得第一個陰影的瞬時位置,需要通過鼠標位置距離h1中心的距離乘以factor係數來獲得,pos表示鼠標當前位置的座標,range指代hero元素的寬和高:
var disX = parseInt((pos.x-range.x/2)*factor);
var disY = parseInt((pos.y-range.y/2)*factor);
4.從事件發生的event對象中獲取需要的值:
var range = {
x:hero.offsetWidth,
y:hero.offsetHeight
}
var pos = {
x:e.target.offsetLeft+e.offsetX,
y:e.target.offsetTop+e.offsetY
}
5.計算出h1元素第一個陰影位置後,可以以座標鏡像或旋轉90°等不同的方式來生成其他陰影,本例中我們採用繞h1元素中心旋轉90°的方式共生成4個陰影:
text.style.textShadow = `
${xWalk}px ${yWalk}px 0 rgba(255,0,255,0.7),
${xWalk * -1}px ${yWalk}px 0 rgba(0,255,255,0.7),
${yWalk}px ${xWalk * -1}px 0 rgba(0,255,0,0.7),
${yWalk * -1}px ${xWalk}px 0 rgba(0,0,255,0.7)
`;
javascript
const hero = document.querySelector('.hero');
const text = hero.querySelector('h1');
const walk = 400;
function shadow(e){
// console.log(e);
// const width = hero.offsetWidth;
// const height = hero.offsetHeight;
const { offsetWidth:width,offsetHeight:height } = hero;
// console.log(hero);
let { offsetX:x,offsetY:y } = e;
// console.log(e);
if(this !== e.target){
// console.log(e);
x = x + e.target.offsetLeft;
y = y + e.target.offsetTop;
}
// console.log(x,y);
const xWalk = Math.round(( x / width * walk) - ( walk / 2));
const yWalk = Math.round(( y / height * walk) - ( walk / 2));
// console.log(xWalk,yWalk);
text.style.textShadow = `
${xWalk}px ${yWalk}px 0px rgba(255,0,255,0.6),
${xWalk * - 1}px ${yWalk}px 0px rgba(0,0,255,0.6),
${yWalk}px ${xWalk * - 1}px 0px rgba(0,0,0,0.6),
${yWalk * - 1}px ${xWalk}px 0px rgba(255,0,0,0.6)
`
}
hero.addEventListener('mousemove',shadow);
var hero = document.querySelector('.hero');
var text = hero.querySelector('h1');
var factor = 0.4;//當鼠標移動至顯示區域邊界時,陰影距離佔hero元素寬和高的比例
//在div範圍內監聽
hero.addEventListener('mousemove',shadowMove);
//文字陰影效果及移動函數
function shadowMove(e){
var range = {
x:hero.offsetWidth,
y:hero.offsetHeight
}
var pos = {
x:e.target.offsetLeft+e.offsetX,
y:e.target.offsetTop+e.offsetY
}
//計算陰影移動距離
var disX = parseInt((pos.x-range.x/2)*factor);
var disY = parseInt((pos.y-range.y/2)*factor);
//修改陰影樣式
text.style.textShadow = disX+'px '+disY+'px 0 #3498db,'+(-disX)+'px '+disY+'px 0 #1abc9c,'+disY+'px '+(-disX)+'px 0 #9b59b6,'+(-disY)+'px '+(-disX)+'px 0 #e74c3c';
}