Floating Menu in PrototypeJS
can someone please help me make a floating menu in prototypeJS? I found documentation to do it in jQuery, like here: net.tutsplus.com/tutorials/html开发者_C百科-css-techniques/creating-a-floating-html-menu-using-jquery-and-css/ and here: manos.malihu.gr/jquery-floating-menu, but can't figure out where to start for prototypeJS.
So I got it work, sorta. I found documentation here. Here's my code:
<html>
<head>
<title>Prototype examples</title>
<script src="lib/prototype/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
Event.observe(window,'scroll', function(evt){
$('movable').setStyle({ top: 8 + document.viewport.getScrollOffsets().top + 'px' });
});
</script>
<style type="text/css">
#container {
background:#000;
padding:100px 10px 10px;
}
#movable {
position: absolute;
float:left;
width:18.5%;
height: 300px;
background-color: red;
}
#firstDiv {
background:#ccc;
float:right;
height:1200px;
width:80%;
}
.clear-both {clear:both;}
</style>
</head>
<body>
<div id="container">
<div id="movable"> Floating menu</div>
<div id="firstDiv">right</div>
<div class="clear-both"></div>
</div>
</body>
</html>
So now I'm trying to get it so it's not choppy when you scroll, and so the menu doesnt start moving until the scroll has moved down to like 100px vertically or something, so it hooks into place.
Figured it out with some help. Used this tutorial: http://jqueryfordesigners.com/fixed-floating-elements/
But changed it up to use Prototype JS syntax. Here's the code:
var topMenu = $('ELEMENT').cumulativeOffset().top;
Event.observe(window,'scroll', function(evt) {
// what the y position of the scroll is
var y = document.viewport.getScrollOffsets().top;
// console.log(y) // console
// check which browser it's using
if (false) { // newer browsers, could be "false"
if (y >= topMenu) {
// if so, ad the fixed class
$('ELEMENT').addClassName('fixed');
} else {
// otherwise remove it
$('ELEMENT').removeClassName('fixed');
}
}
else { // older browsers, iPad, iPhone
if (y >= topMenu) {
$('ELEMENT').setStyle({ top: (0 + document.viewport.getScrollOffsets().top - topMenu) + 'px' });
}
else {
$('ELEMENT').setStyle({ top: 0 + 'px' });
}
}
});
If you want it to not look choppy, you're going to have to use an animation library. If you're using Prototype, then your best bet is to look into Scriptaculous at http://script.aculo.us/
I'd also recommend using Element.cumulativeOffset on DOM load to get the absolute top offset of the menu. Then each time you scroll the menu element, include this initial padding so the menu doesn't just latch on to the top of the viewport.
One more idea too, if you don't particularly want to use an animation library, you could try making the menu position: fixed. You'll still have to keep updating the position for IE though, as it doesn't support fixed positioning ...
精彩评论