どうして競合するのか?よく質問されるので、いまさらですがまとめてみました。
私は「3」をテンプレとして使っております。
1. 「$」を「jQuery」置き換える。
簡単に言うとDOM構造内で「$」バッティングしているのが原因なので、
「$」を「jQuery」置き換えれば実装されます。
(「jQuery」じゃなくても「$」を変数化して「$j」とかでもOK)
つまり、(rollover.jsの場合)
$(function(){ $("img.rollover").mouseover(function(){ $(this).attr("src",$(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2")); }).mouseout(function(){ $(this).attr("src",$(this).attr("src").replace(/^(.+)_on(\.[a-z]+)$/, "$1$2")); }).each(function(){ $("<img>").attr("src",$(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2")); }); });
jQuery(function(){ jQuery("img.rollover").mouseover(function(){ jQuery(this).attr("src",jQuery(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2")); }).mouseout(function(){ jQuery(this).attr("src",jQuery(this).attr("src").replace(/^(.+)_on(\.[a-z]+)$/, "$1$2")); }).each(function(){ jQuery("<img>").attr("src",jQuery(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2")); }); });
2.「$」を使いたいなら「.noConflict」関数を使う。
*rolloverだけじゃなくバッティングする「$」すべてこのやり方でOKです。
jQuery.noConflict(); (function($) { // この間に「$」を使ったjQueryのコードを書くことができます。 })(jQuery);
jQuery.noConflict(); (function($) { $(function(){ $("img.rollover").mouseover(function(){ $(this).attr("src",$(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2")); }).mouseout(function(){ $(this).attr("src",$(this).attr("src").replace(/^(.+)_on(\.[a-z]+)$/, "$1$2")); }).each(function(){ $("<img>").attr("src",$(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2")); }); }); })(jQuery);
3. それも面倒であれば、java Scriptで書く。
私は面倒なので、画像置換に関しては
java Scriptで書いている↓smartRolloverをデフォルトで使っています。
(「.noConflict」はそれ以外のライブラリがバッティングした時に使っています。)
function smartRollover() { if(document.getElementsByTagName) { var images = document.getElementsByTagName("img"); for(var i=0; i < images.length; i++) { if(images[i].getAttribute("src").match("_off.")) { images[i].onmouseover = function() { this.setAttribute("src", this.getAttribute("src").replace("_off.", "_on.")); } images[i].onmouseout = function() { this.setAttribute("src", this.getAttribute("src").replace("_on.", "_off.")); } } } } } if(window.addEventListener) { window.addEventListener("load", smartRollover, false); } else if(window.attachEvent) { window.attachEvent("onload", smartRollover); }
*こちらだと通常にも「_off」を付ける必要がありますが、imgにクラス名をつけなくていいので楽です。
*通常時の画像名→○○_off、hover時→○○_on、imgのクラス名→必要なし。
あと、↓こちらはrollover.jsをカスタマイズしたものです。
*通常時の画像名→○○、hover時→○○_on、imgのクラス名→rollover
function initRollOverImages() { var image_cache = new Object(); $("img.rollover").each(function(i) { var imgsrc = this.src; var dot = this.src.lastIndexOf('.'); var imgsrc_on = this.src.substr(0, dot) + '_on' + this.src.substr(dot, 4); image_cache[this.src] = new Image(); image_cache[this.src].src = imgsrc_on; $(this).hover( function() { this.src = imgsrc_on; }, function() { this.src = imgsrc; }); }); } $(document).ready(initRollOverImages);
▼参考URL
http://allabout.co.jp/gm/gc/24167/
http://js.studio-kingdom.com/jquery/core/no_conflict
http://bizarrewitch.com/?p=588