本文最后更新于2022年6月5日,已超过 1 年没有更新,如果文章内容失效,请 反馈 给我们,谢谢!
导航菜单当鼠标划过时自动播放哆唻咪发嗖拉嘻等音频,鼠标划动经过菜单栏时会有钢琴的音乐,纯JS实现不需要媒体文件。
全部代码如下:
body,html{font-family:Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Noto Sans CJK SC,WenQuanYi Micro Hei,Arial,sans-serif;padding:0 0;margin:0 auto;color:#000;font-size:16px;} ul{line-height:180%;margin-top:0;} a:link{color:#000;text-decoration:none;} a:visited{color:#999;text-decoration:none;} a:hover{color:#F00;text-decoration:underline;} a:active{color:#ff0000;text-decoration:underline;} .clear{clear:both;width:0;height:0;margin:0 0;padding:0 0;} #header{margin:0px auto;} #menu{background-color:#F5F5F5;border:0;} #menu ul{padding:0 0;list-style-type:none;margin:0px;} #menu ul li{float:left;position:relative;border:0 solid #999;border-width:1px 1px 1px 0;} #menu ul li a{padding:6px 18px;display:block;float:left;color:#0c0c0c;font-size:15px;font-weight:bold;text-decoration:none;} #menu a:hover{background:#eb1d1d;color:#ffffff;text-decoration:none;} .current_page_item{background:#eb1d1d;color:#ffffff;text-decoration:none;} #menu a.current_page_item{color:#ffffff;}
<div id="menu"> <ul> <li style="border-left:1px solid #999;"> <a href="/"> 小么小儿 </a> <div class="clear"> </div> </li> <li> <a href="/php/"> 郎背着那 </a> <div class="clear"> </div> </li> <li> <a href="/database/"> 书包进学 </a> <div class="clear"> </div> </li> <li> <a href="/javascript/"> 堂不怕太 </a> <div class="clear"> </div> </li> <li> <a href="/html/"> 阳晒也不 </a> <div class="clear"> </div> </li> <li> <a href="/operating-system/"> 怕那风雨 </a> <div class="clear"> </div> </li> <li> <a href="/go/"> 狂 </a> <div class="clear"> </div> </li> </ul> <div class="clear"> </div> </div>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.12.4/jquery-1.12.4.min.js"></script>
$(function() { if (window.AudioContext) { var audioCtx = new AudioContext(); var arrFrequency = [196, 220, 246.94, 261.63, 293.66, 329.63, 349.23, 392, 440, 493.88, 523.25, 587.33, 659.25, 698.46, 783.99, 880, 987.77, 1046.5]; var start = 0, direction = 1; var tagList = document.querySelectorAll("#menu ul li"); for (var i = 0; i < tagList.length; i++) { tagList[i].addEventListener("mouseenter", function() { var frequency = arrFrequency[start]; if (!frequency) { direction = -1 * direction; start = start + 2 * direction; frequency = arrFrequency[start] } start = start + direction; var oscillator = audioCtx.createOscillator(); var gainNode = audioCtx.createGain(); oscillator.connect(gainNode); gainNode.connect(audioCtx.destination); oscillator.type = "sine"; oscillator.frequency.value = frequency; gainNode.gain.setValueAtTime(0, audioCtx.currentTime); gainNode.gain.linearRampToValueAtTime(1, audioCtx.currentTime + 0.01); oscillator.start(audioCtx.currentTime); gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 1); oscillator.stop(audioCtx.currentTime + 1) }) } } });