<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title><style type="text/css"><!--body { margin:0 auto; padding:0;}.test { width:800px; height:2000px; background:#999999;}.test1 { width:100px; height:2000px; background:#0000CC; float:left;}.test2 { width:650px; height:2000px; background:#CC0000; float:right;}.test3 { width:150px; height:150px; background:#CC9900; float:right;}--></style></head><body><div class="test"><div class="test1"></div><div class="test2"><div class="test3"></div></div></div>我想让test3这个div随着网页的下拉滚动而随着滚动,求js代码。</body></html>
In fact, you don’t need js code. Use CSS to fix the positioning
For reference
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title><style type="text/css"><!--body { margin:0 auto; padding:0;}.test { width:800px; height:2000px; background:#999999;}.test1 { width:100px; height:2000px; background:#0000CC; float:left;}.test2 { width:650px; height:2000px; background:#CC0000; float:right;}.test3 { width:150px; height:150px; background:#CC9900; float:right;}--></style></head> <body><div class="test"><div class="test1"></div><div class="test2"><div class="test3" id="test"></div></div></div>我想让test3这个div随着网页的下拉滚动而随着滚动,求js代码。<script> function toolbar(el){ el = typeof el == 'string' ? document.getElementById(el) : el; var elTop = el.offsetTop; var sTop = 0; window.onscroll = function(){ sTop = document.body.scrollTop || document.documentElement.scrollTop; if( sTop > elTop ){ el.style.marginTop = sTop + 'px'; }else{ el.style.marginTop = elTop + 'px'; } } } toolbar('test');</script></body></html>