JavaScript事件委託 單元素多種變化

這篇文章主要介紹事件委託 及元素的多種樣式改變


	<div class="main">
		<span class="block0"></span>
		<span class="block1"></span>
		<span class="block2"></span>
	</div>

下面是CSS部分代碼

		.main{
			width: 400px;
			height: 800px;
			position: relative;
			top: 100px;
			left: 100px;
			cursor: pointer;
		}
		.block0,.block1,.block2{
			display: block;
			width: 100px;
			height: 100px;
			border-radius: 20px;
			opacity: 1;
			margin-bottom: 100px;
		}
		.block0{background-color: #D24D57;}
		.block1{background-color: #fc9d99;}
		.block2{background-color: #aedd81}

然後給大家看一下效果圖

在這裏插入圖片描述
JavaScript部分

var main = document.getElementsByClassName("main")[0];
		var timer = null;
		main.onclick = function(ev){
	        var ev = ev || window.event;    
	        var target = ev.target || ev.srcElement;
	        if(target.nodeName.toLowerCase() == 'span'){ 
	            move(target,{width:180,height:180,borderRadius:90,opacity:60})
	        }
	    }
	    function move(ele,attrobj){
	    	clearInterval(ele.timer);
	    	ele.timer = setInterval(function(){
	    		var istop = true;
	    		let ispeed = null,icur = null;
	    		for(let attr in attrobj){
	    			if(attr != "opacity"){
	    				icur = parseFloat(getStyle(ele,attr));
	    				console.log(icur)
	    			}else{	
	    				icur = parseFloat(getStyle(ele,attr))*100;
	    			}
	    			ispeed = (attrobj[attr]-icur)/7;
	    			ispeed = ispeed > 0 ? Math.ceil(ispeed):Math.floor(ispeed);
	    			if(attr != "opacity"){
	    				ele.style[attr] = icur + ispeed + "px";	
	    			}else{
	    				ele.style.opacity = (icur + ispeed)/100;
	    			}
	    			if (icur != attrobj[attr]) {
	    				istop = false;
	    			}
	    		}
	    		if (istop) {
	    			clearInterval(ele.timer);
	    		}
	    	},40)
	    }
	    function getStyle(elem,prop){
	    	if (window.getComputedStyle) {
	    		return window.getComputedStyle(elem)[prop];
	    	}else{
	    		return elem.currentStyle[prop];
	    	}
	    }

我們爲父元素main添加委託事件 使他的子元素擁有這些實踐 但是爲了防止我們點到空白位置觸發父元素的事件 所以做了一層判斷(只有當它的節點爲span時纔會觸發)
然後下面的move函數則是讓我們所有的變化有一個過程展示(在裏面添加了一個僞速度變量) 避免瞬間完成。然後我們把要改變的樣式封成一個對象傳給move函數進行for in 循環 遍歷每一個屬性值
if (icur != attrobj[attr]) {
istop = false;
}
這段代碼則是爲了使每一種變化效果都完成後改變狀態來判斷該不該清除當前元素的定時器
最後的getStyle函數大家可以直接使用 用來獲得某一個元素的某一個樣式

在這裏插入圖片描述
點擊子元素後如上


如有錯誤,請指正!
發佈了26 篇原創文章 · 獲贊 23 · 訪問量 959
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章