プログラミングの経験がほとんどないjQueryの新機能ですので、考慮してください。 imgelement
このスクリプトを一般化することは可能でしょうか?
2)ホバー画像の画像URL - - hoverimageurl
1)の要素():
は、私は次の2つの変数を取る時間を節約するスクリプトを作成しましたコード:
/* Image Hover Script (Start) */
var imgelement = "#element"; /* Element containing the original image */
var hoverimageurl = "http://www.domain.com/image.png2"; /* Image URL of the hover image */
jQuery(document).ready(function() {
\t /* Add CSS and a class to the original image to fix positioning and give it an identification */
\t jQuery(imgelement + " img").addClass("originalimage");
\t \t
\t /* Prepend hover image to the element. Set the SRC to the hover image URL */
\t jQuery(imgelement).prepend('<img class="hoverimage" src="' + hoverimageurl + '">');
\t
\t /* Fade out original image and fade in hover image on hover */
\t jQuery(imgelement).hover(function() {
\t \t jQuery(imgelement + " .originalimage").stop(true).fadeTo(1000, 0);
\t \t jQuery(imgelement + " .hoverimage").stop(true).fadeTo(1000, 1);
\t }, function() {
\t \t jQuery(imgelement + " .hoverimage").stop(true).fadeTo(1000, 0);
\t \t jQuery(imgelement + " .originalimage").stop(true).fadeTo(1000, 1);
\t });
\t
});
/* Image Hover Script (End) */
/* Image Hover CSS (Start) */
#pix-fe .originalimage {
\t position: relative;
}
#pix-fe .hoverimage {
\t position: absolute;
\t width: 100%;
\t height: 100%;
}
/* Image Hover CSS (End) */
<div class="element">
<a href="http://www.domain.com"><img src="http://www.domain.com/image1.png"></a>
</div>
要素がホバリングされたときに変数hoverimageurl
から与えられたホバーイメージにフェードインします。これは完全に機能しますが、私はこのスクリプトの複数のインスタンスを使用し、そうするために、必要なインスタンスごとに変数名を増やす必要があります。理想的には、変数リストとメインスクリプトの1つのインスタンスが理想的である場合、スクリプトの大部分をインスタンスごとに繰り返す必要があるため、これは非効率的です。
このコードを一般化する方法はありますか?私はthis
を認識していますが、imgelement
は常にimgelement
という変数に対して値を参照するため、私の知る限り、これをどのように行うことができないのか分かりません。
ありがとうございます。
私はあなたがこれを乾燥させることができると確信しているが、我々がする必要があるだろうあなたのHTMLも見てください。あなたの質問を編集してそれを含めてください。 –
セレクタをよりきつくフィットさせようとするとどうなりますか?例: '#element:hover'を対象にしていますか?この場合、 'this'は単一のインスタンスを参照すべきではありませんか? – Seth
@sethセレクタは既に間違っています。 IDは一意でなければなりません。クラスがより良くなり、 '$( 'example')と推測しています。それぞれ(function(){console.log(this)})'が最良の結果を得ます。 –