使用js代码制作H5页面的底部滑动面板。

百度地图这个应用上,有个点击了某个地点后,会在底部弹出一个滑动面板,这个面板可以滑动,然后我就是使用了js代码,制作了一个功能一样的、h5页面上的滑动面板。我看了百度上一些js实现滑动面板的代码,学习了一下,就开始使用了。

直接上代码讲了。

首先html定义一个div作为滑动面板。

这个div之所以能够滑动,其实就是改变了他的top属性和height属性,当top减少1px,height增加1px时,他看上去就是被拖上去了1px。

所以我们只需要捕捉到移动端的单击、滑动、离开等动作,就可以进行判断该如果去控制滑动面板的属性了。而捕捉那些动作的api是也是现成的。也就是touchstart,touchmove和touchend三个。接下来上关键代码:

//滑动开始事件  mobile
    function touchStart(e) {  
    	 
        if(countClick == 1 && e.touches[0].clientY >= parseInt(slideBoard.style.top)){
        	
        	
        	mobileOldY = e.touches[0].clientY;
        	moblieTop = parseInt(slideBoard.style.top);
        	mobileOldTIME = new Date().getTime();
    		
        	document.addEventListener('touchmove', touchMove);  
        	
            document.addEventListener('touchend', touchEnd);  
        }
    }  
    function touchMove(e){
    	e.preventDefault();
		var y = e.touches[0].clientY - mobileOldY;
		slideBoard.style.top = moblieTop + y + "px";
		slideBoard.style.height = $(window).height() - y - moblieTop + "px";
		if (parseInt(slideBoard.style.top) < 0) {
			slideBoard.style.top = 0;
		}
		if (parseInt(slideBoard.style.top) > Math.ceil($(window).height()
				* initRate)) {
			slideBoard.style.top = Math.ceil($(window).height() * initRate) + "px";
			slideBoard.style.height = Math.ceil($(window).height() * (1 - initRate)) + "px";
		}
    }
    
    function touchEnd(e){
    	
    	document.removeEventListener('touchmove', touchMove);  
        document.removeEventListener('touchend', touchEnd);
    	var dist = mobileOldY - e.changedTouches[0].clientY;
    	var time = new Date().getTime() - mobileOldTIME; 
        if(dist/time > 0.5){
        	moveSlideBoardTo(2);
        	return;
        }
        if(dist/time < -0.5){
        	moveSlideBoardTo(0);
        	return;
        }
        if(parseInt(slideBoard.style.top) < Math.ceil($(window).height() * 0.1) ){
        	moveSlideBoardTo(2);
        }else if(parseInt(slideBoard.style.top) < Math.ceil($(window).height() * 0.5) ){
        	moveSlideBoardTo(1);
        }else{
        	moveSlideBoardTo(0);
        }
        
        
    }

其中moveSlideBoardTo函数是让滑动面板的top等于某个特定的值的,因为我想学百度地图那样,使滑动面板会移动到固定的3个位置,其实分别就是初始位置、80%的位置,
和顶部。
这段代码的逻辑主要就是当手触屏的时候开始判断是否落在面板区域内,如果是的话,手指如果滑动,就进行跟着手指使面板的top和height属性进行相同变化,这样就看上去
是跟着手指在动了。

你可能感兴趣的:(web前端)