6:00~朝6:00までは yoru.css を読み込むような
ジャバスクリプトを書きたいのですが、
どのように記述したらよいのかわかりません。
教えてください。
こんな感じでしょうか。
<script> function addStyleSheet(s) { var e = document.createElement("LINK"); e.rel = "stylesheet"; e.type = "text/css"; e.href = s; document.head.appendChild(e); } window.onload = function() { var now = new Date(); // 今の時刻 var hour = now.getHours(); // 今の時刻の「時」(0~23) if (6 <= hour && hour <= 18) { // 朝 6:00 から、夕方 6:00 まで addStyleSheet("hiru.css"); } else { addStyleSheet("yoru.css"); } }; </script>
<html lang="ja"> <head> <script> window.addEventListener('load', init, false); function init() { var style = document.createElement('link'); style.type = 'text/css'; style.rel = 'stylesheet' var d = new Date(); var hour = d.getHours(); style.href = (hour >= 6 && hour <= 18) ? 'hiru.css' : 'yoru.css'; document.head.appendChild(style); } </script> </head> <body> <h1>人力検索はてな</h1> </body> </html>