문제

나는 컬러 이미지를 가져 오는 동작을 만들려고 노력하고 있으며 일단 호버가 제거되면 원래 이미지로 다시 사라집니다.

현재 그것은 이미지를 아무것도 퇴색시키고 새로운 것을 사라지는 다음 이미지를 사라집니다. 이것은 내가 떠나는 지 여부에 관계없이 제자리에 머무를 것입니다.

//Loop through the images and print them to the page
   for (var i=0; i < totalBoxes; i++){
    $.ajax({
     url: "random.php?no=",
     cache: false,
     success: function(html) {
      // following line I originally suggested, but let's make it better...
      //$('#bg').append(html).fadeIn('slow');
      // also note the fine difference between append and appendTo.
      var $d = $(html).hide().appendTo('#bg').fadeIn('slow');
      $('img', $d).hover(function() {
       var largePath = $(this).attr("rel");
       $(this).fadeOut("slow", function() {
        $(this).attr({ src: largePath }).fadeIn("slow");
       });
      });
     }
    });
   }

업데이트:

이 링크를 살펴보십시오.

http://www.yellostudio.co.uk/temp/index.php#

나는 이미지가 롤오버에서 페이드 인을 교차시키고 페이드 아웃에서 나가려고 노력하고있다 ...

누구든지 도와 줄 수 있습니까, 나는 너무 가까이서 나는이 주위에 내 머리를 잡으려고 몇 시간과 몇 시간을 보냈습니다 ...

도움이 되었습니까?

해결책 7

당신의 도움을 주신 여러분 모두에게 감사합니다 ... 나는 어딘가에 있습니다 ... 나는 원래 의도 한 것보다 느리게 행복하지 않습니다. 더 빨리 호버에 이미지를로드하고 있었기 때문에 ...

하지만 여러분 모두 덕분에 해결책이 있습니다 ...

          //Loop through the images and print them to the page
        for (var i=0; i < totalBoxes; i++){
            $.ajax({
                url: "random.php?no=",
                cache: false,
                success: function(html) {

                    var $d = $(html).hide().appendTo('#bg').fadeIn('slow');
                    $('#colour img').css("opacity", 0);
                    $('img', $d).hover(function() { 
                        $(this).stop().fadeTo(700, 1);
                    },function() {
                        $(this).stop().fadeTo(700, 0);
                    });

                }
            });
        }

그리고 내 PHP 인쇄 ...

<div class="pf-box">
    <a href="#">
    <div class="black"><img src="'.$image_folder.'/'.$image_name.'.jpg" alt="'.$image_name.'" border="0" /></div>
    <div class="colour"><img src="'.$image_folder.'/'.$image_name.'-c.jpg" alt="'.$image_name.'" border="0" /></div>
    </a>
  </div>

다른 팁

hover() 하나는 두 가지 함수 매개 변수를 사용합니다 mouseover 그리고 다른 하나는 mouseout. 당신은 첫 번째를 제공했습니다. 이미지 스와핑을 취소하려면 두 번째를 공급해야합니다. mouseout.

당신이 원한다면 fadeOut 그리고 fadeIn 동시에 말하지 마십시오 fadeIn 콜백에서 fadeOut. 별도의 진술을 만드십시오.

$(this).fadeOut("slow");
$(this).attr({ src: largePath }).fadeIn("slow");

당신이 가지고있는 방식, fadeIn 까지 시작하지 않습니다 fadeOut 수행. 이런 식으로, 그들은 동시에 시작하고 끝날 것입니다.

원래 이미지 경로를 저장해야한다고 생각합니다.

var $d = $(html).hide().appendTo('#bg').fadeIn('slow');
$('img', $d).hover(function() {
    var largePath = $(this).attr("rel");
    $(this).data('orig', $(this).attr('src') );
    $(this).fadeOut("slow", function() {
         $(this).attr({ src: largePath }).fadeIn("slow");
     });
},function() {
    var origPath = $(this).data('orig');
    $(this).fadeOut("slow", function() {
         $(this).attr({ src: origPath }).fadeIn("slow");
     });
});

"밝은"이미지가 SRC 속성으로 사용되며 불투명도를 사용하여 효과를 달성한다고 가정합니다.

var $d = $(html).hide().appendTo('#bg');
$('img',$d).css('opacity',0.33);
           .hover( function() {
               $(this).fadeTo('slow',1.0);
            }, function() {
               $(this).fadeTo('slow',0.33);
            });

제안 할 수 있습니다 : http://colorpowered.com/blend/

그것은 당신이 찾고자하는 일을 할 것입니다.


편집하다:좋아, 글쎄, 나는 코드의 ajax 부분을 확실히 JSON을 통해 모든 이미지를 반환하도록 할 것입니다 (더 나은 백엔드에서는 더 나은 것이지만, 귀하의 사이트가 어떻습니까? 설정). 어쨌든, 당신이 다른 이미지를 불필요하게 사라지는 것처럼 보입니다. 절대 위치로 다른 이미지 위에 색상 이미지를 배치하기 만하면됩니다. 코드가 다음과 같이 보일 수 있습니다.

자바 스크립트 :

$.ajaxSetup({cache:false});
$('.hoverImg').live('mouseover',function() {
   $hovered = $(this);
   var colorPath = $hovered.attr("rel");
   var rndId = Math.floor(Math.random()*100000);
   var $colorImg = $('<img />');
   $colorImg
       .hide()
       .addClass("fader")
       .attr('src',colorPath)
       .attr('id','img_'+rndId)
       .css({position:'absolute',zIndex:10});
   $hovered.css({zIndex:9}).data('overImgId',rndId).before($colorImg);
   $('#img_'+rndId).stop().fadeIn("slow");
});
$('.hoverImg').live('mouseout',function() {
    var rndId = $(this).data('overImgId')
    $('#img_'+rndId).stop().fadeOut("slow");
});
$.getJSON('random.php',{numBoxes:totalBoxes},function(json) {
    if(json.length > 0) {
        $.each(json,function(i,val) {
            $(val).hide().appendTo('#bg').find('img').addClass('hoverImg');
        });
    }
});

PHP :

<?php //random.php (really simplified, probably)
if(isset($_GET['numBoxes']) && !empty($_GET['numBoxes'])) {
    /*
        Get all the html stuff you need into an array...
        Could look something like:
        $imgs = array(
            '<div><img src="foo.jpg" rel="color_foo.jpg" /></div>',
            '<div><img src="bar.jpg" rel="color_bar.jpg" /></div>'
        );
    */
    echo json_encode($imgs);
}

기본적으로 작동해야합니다. 거기에 약간의 오타와 물건이있을 수 있지만, 내가 말할 수있는 것에서는 효과가 있어야합니다. 물론 시나리오에 따라 일부를 조정/변경해야 할 수도 있습니다.

프로젝트에 행운을 빕니다!

중요한 편집 : PHP 코드에 핵심 부분을 추가하는 것을 잊었습니다. "Rel"attrs를 추가했습니다 <img> 태그.

추가 코드를 사용하여이를 수행 할 수 있습니다. 불투명도가 0으로 설정된 페이드 아웃 이미지 위에 페이드 인 이미지를 배치하십시오. 호버 코드를 페이드 인 이미지에 추가하십시오 (상단에 있으므로 이벤트가 가져옵니다).

$('#top-image').hover(function() {
$(this).stop().fadeTo(1000, 1);
$('#bottom-image').stop().fadeTo(1000, 0);
},
function() {
$(this).stop().fadeTo(1000, 0);
$('#bottom-image').stop().fadeTo(1000, 1);
});

두 이미지가 모두 끊어지고 아웃되며 정지 () 함수를 사용하면 빠르게 마시는 것은 일련의 반복 애니메이션으로 이어지지 않습니다.

크로스 페이드를하고 싶다면 두 개의 이미지가 필요합니다. 하나는 희미 해지고 하나는 동시에 사라지는 이미지가 필요합니다. a 내가 한 페이지 이 효과로. 내가 쓴 플러그인은 페이지 소스에 바로 이루어 지므로 볼 수 있습니다. 두 이미지에는 있어야합니다 position: absolute; 그래서 그들이 교차로 이탈함에 따라 그들은 페이지의 동일한 영역을 차지할 수 있습니다.

그리고 놀라움이 말하지 않은 것처럼, 당신은 콜백을 제공하고 있습니다. hover 마우스 호버의 경우, 원본으로 교차로 다시 생산하는 마우스 un-hover가 아닙니다.

이 코드는 작동하고 CSS의 절대 포지셔닝을 기억할 수 있으며 CSS 클래스를 BackIMG에 추가 할 수 있으며 이미지는 호버 이벤트가 구독하는 개별 부모 요소에 있어야합니다.

for (var i=0; i < totalBoxes; i++){
    $.ajax({
        url: "random.php?no=",
        cache: false,
        success: function(html) {
            $(html)
                .hide()
                .appendTo('#bg')
                .fadeIn('slow')
                .children('img').each(function() {
                    var img = $(this);
                    var largePath = img.attr("rel");
                    var backImg = $("<img src='" + largePath + "'/>");
                    img.after(backImg);

                    img.parent().hover(
                        function() { // over
                            backImg.stop().fadeIn("slow");
                            img.stop().fadeOut("slow");
                        },
                        function() { // out
                            backImg.stop().fadeOut("slow");
                            img.stop().fadeIn("slow");
                        }
                    );
                });
        }
    });
}

나는 여기서 문제를 발견했다 ...

var backImg = $("<img src='" + largePath + "'/>");

이것은 유효한 선택기가 아닙니다. 대신 시도해보십시오.

var backImg = $('img[src="' + largePath + '"]');

선택기에서 <>를 사용하고 싶지 않으며 속성 선택기 구문은 다음과 같습니다. [attr = "value"
당신은 내가 '내 코드에서 사용하는 것을 뒤집 었다는 점에 유의해야합니다. 그것은 내가하는 방식입니다. 그것은 구문 적으로 동일합니다. 당신의 선택에 아무런 문제가 없습니다.

스타일 시트에서 추가 :

.colour {
  display:none;
}

그런 다음 성공 기능을 읽게하십시오.

var $d = $(html).hide().appendTo('#bg').fadeIn('slow');
$('.pf-box', $d).hover(function() {
  $('.colour', $(this)).fadeIn("slow");      
},function() {
  $('.colour', $(this)).fadeOut("slow");      
});

업데이트

느린 로딩 문제를 해결하려면 PHP가 SO와 같은 모든 이미지의 객체를 반환하도록해야합니다 (images.php라고 가정 해 봅시다. <?php ?>) (JSON_ENCODE ()를 사용하고 싶지만 이전 버전의 PHP에있었습니다) :

header('Content-type: application/json');
echo '{
  {'black' : 'url', 'colour' : 'url'},
  {'black' : 'url2', 'colour' : 'url2'}
}';

그런 다음 JavaScript에서 원하는 것입니다.

//generate all the boxes
$.get('images.php',function(data){
  for (var i=0; i < totalBoxes; i++){
      var randomImage = data[Math.floor(Math.random() * data.length)];
      $('<div class="pf-box"><img class="black" src="' + randomImage['black'] + '" /><img class="colour" src="' + randomImage['colour'] + '" /></div>').hide().appendTo('#bg').fadeIn('slow').filter('.colour').css("opacity", 0);
  }
 },'json');

 //add the hover behavior to all the elements
 $('.pf-box').hover(function() {
   $('.colour',$(this)).stop().fadeTo(700, 1);
 },function() {
   $('.colour',$(this)).stop().fadeTo(700, 0);
 });

이 코드는 작동해야하지만 테스트하지 않았습니다. 오타가있을 수 있습니다. 그러나 이것은 그것의 요점입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top