ITeye博客

滚动内容的问题

katelin · 2007-10-23 11:09 · Javascript · Web前端 · Markdown

常常看到window的菜单如果太长了下面(或上面)就会出现滚动的小三角。鼠标移上的时候菜单就会滚动。这个效果用js也可以模枋。


<div id="box" style="width:200px;height:200px;border:solid 1px;overflow:auto;">
	<script>
		for(var i = 0;i < 30;i++){
			document.write(i + '<br/>');
		}
	</script>
</div>
<button onmouseover="down()" onmouseout="stop()" id="scrollButton">向下scroll</button>

<SCRIPT LANGUAGE="JavaScript">
<!--
	var box = document.getElementById('box');
	var scrollButton = document.getElementById('scrollButton');

	function scrollDown(){
		var _top = box.scrollTop;
		box.scrollTop = _top + 20;
		window.status = 'height:'+ box.scrollHeight + ', top:' + box.scrollTop;
	}
	
	var timer;
	function down(){
		timer = window.setInterval("scrollDown()", 100);
	}

	function stop(){
		window.clearInterval(timer);
	}
//-->
</SCRIPT>

这个例子里,当鼠标移上按钮的时候,就用定时器每隔0.1秒去改变容器的scrollTop,移开的时候就把这个定时器去掉就okay了。

这里有个问题,我要怎么样知道滚动条已经到了容器的最底部?当滚动条到底时,可以从打印在状态栏的信息里看到容器的scrollHeight大于这时的scrollTop啊。

郁闷,从博客写的贴子没办法预览。带html的代码也不能贴。前面那贴弄坏了,请管理员删除一下。不好意思。

论坛里的倒是可以贴html代码。难道只能从论坛写了再转到自己的博客里?

评论(1)

  1. #1 楼 · katelin · 2007-10-23 11:37

    明白了。原来是要再加上容器高度和border的宽度。

    最后的例子是:

    
    
    <div id="box" style="width:200px;height:200px;border:solid 1px;overflow:auto;">
    	<script>
    		for(var i = 0;i < 30;i++){
    			document.write(i + '<br/>');
    		}
    	</script>
    </div>
    <button onmouseover="down()" onmouseout="stop()" id="scrollButton">向下scroll</button>
    
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    	var box = document.getElementById('box');
    	var scrollButton = document.getElementById('scrollButton');
    
    	function scrollDown(){
    		var _top = box.scrollTop;
    		box.scrollTop = _top + 20;
    
    		var _borderHeight = parseFloat(box.style.borderWidth) * 2;
    		if(_borderHeight + box.style.pixelHeight + box.scrollTop >= box.scrollHeight){
    			scrollButton.innerText = '向上scroll';
    			stop();
    			up();
    		}
    	}
    
    	function scrollUp(){
    		var _top = box.scrollTop;
    		box.scrollTop = _top - 20;
    		
    		if(box.scrollTop == 0){
    			scrollButton.innerText = '向下scroll';
    			stop();
    			down();
    		}
    	}
    	
    	var timer;
    	function down(){
    		timer = window.setInterval("scrollDown()", 100);
    	}
    
    	function up(){
    		timer = window.setInterval("scrollUp()", 100);
    	}
    
    	function stop(){
    		window.clearInterval(timer);
    	}
    //-->
    </SCRIPT>
    
    
    

    鼠标移至按钮上,滚动条会向下移动。到底时滚动条会再向上移动。依此反复。

评论功能维护中,当前仅展示历史评论。