@ssclock

Как сделать, чтобы скрипт не оставлял лишние div?

Не зная js как-то удалось приделать данный скрипт (зуминг изображений) к лайтбокс-галерее и даже сделать ходящий за курсором div с увеличенным фрагментом (.imagezoom-view). Только вот вместо просто изменения позиции этого div'а с каждым передвижением он множится, и в DOM остаётся висеть много старых, что недопустимо.
Что и куда надо добавить, чтобы убрать этот эффект?

/**
 * ImageZoom Plugin
 * http://0401morita.github.io/imagezoom-plugin
 * MIT licensed
 *
 * Copyright (C) 2014 http://0401morita.github.io/imagezoom-plugin A project by Yosuke Morita
 */
(function($){
  var defaults = {
    cursorcolor:'255,255,255',
    opacity:0.5,
    cursor:'crosshair',
    zindex:2147483647,
    zoomviewsize:[100,50],
    zoomviewmargin:2,
    zoomviewborder:'none',
    magnification:2
  };

  var imagezoomCursor,imagezoomView,settings,imageWidth,imageHeight,offset;
  var methods = {
    init : function(options){
      $this = $(this),
      imagezoomCursor = $('.imagezoom-cursor'),
      imagezoomView = $('.imagezoom-view'),
      $(document).on('mouseenter',$this.selector,function(e){
        var data = $(this).data();
        settings = $.extend({},defaults,options,data),
        offset = $(this).offset(),
        imageWidth = $(this).width(),
        imageHeight = $(this).height(),
        cursorSize = [(settings.zoomviewsize[0]/settings.magnification),(settings.zoomviewsize[1]/settings.magnification)];
        if(data.imagezoom == true){
          imageSrc = $(this).attr('src');
        }else{
          imageSrc = $(this).get(0).getAttribute('data-imagezoom');
        }

        var posX = e.pageX,posY = e.pageY,zoomViewPositionX;
      var posYY = (posY - 40);
        $('body').prepend('<div class="imagezoom-view"><img src="'+imageSrc+'"></div>');

        
        var zoomViewPositionX = (offset.left-imageWidth-settings.zoomviewmargin+80);
        var zoomWidth = ((imageWidth)/2.2);
        var zoomHeight = ((imageHeight)/2.2);
        
        
        $(imagezoomView.selector).css({
          'position':'absolute',
          'width': '100',
          'height': '100',
          'background':'#000',
          'z-index':2147483647,
          'overflow':'hidden',
        });

        $(imagezoomView.selector).children('img').css({
          'position':'absolute',
          'width': imageWidth*settings.magnification,
          'height': imageHeight*settings.magnification,
        });

        $(imagezoomCursor.selector).css({
          'position':'absolute',
          'width':cursorSize[0],
          'height':cursorSize[1],
          'background-color':'rgb('+settings.cursorcolor+')',
          'z-index':settings.zindex,
          'opacity':settings.opacity,
          'cursor':settings.cursor
        });
        
        $(imagezoomCursor.selector).css({'top':posYY-(cursorSize[1]/2),'left':posX});
        $(document).on('mousemove',document.body,methods.cursorPos);
      });
    },
    
    cursorPos:function(e){
      var posX = e.pageX,posY = e.pageY;
      var posYY = (posY - 40);
      if(posYY < (offset.top-40) || posX < (offset.left-40) || posYY > (offset.top+imageHeight+40) || posX > (offset.left+imageWidth+40)){
        $(imagezoomCursor.selector).remove();
        $(imagezoomView.selector).remove();
        return;
      }

      if(posX-(cursorSize[0]/2) < offset.left){
        posX = offset.left+(cursorSize[0]/2);
      }else if(posX+(cursorSize[0]/2) > offset.left+imageWidth){
        posX = (offset.left+imageWidth)-(cursorSize[0]/2);
      }

      if(posYY-(cursorSize[1]/2) < offset.top){
        posYY = offset.top+(cursorSize[1]/2);
      }else if(posYY+(cursorSize[1]/2) > offset.top+imageHeight){
        posYY = (offset.top+imageHeight)-(cursorSize[1]/2);
      }

      
      $(imagezoomView.selector).children('img').css({'top':((offset.top-posYY)+(cursorSize[1]/2))*settings.magnification,'left':((offset.left-posX)+(cursorSize[0]/2))*settings.magnification});

      $(imagezoomCursor.selector).mouseleave(function(){
        $(this).remove();
      });
    }
  };

  $.fn.imageZoom = function(method){
    if(methods[method]){
      return methods[method].apply( this, Array.prototype.slice.call(arguments,1));
    }else if( typeof method === 'object' || ! method ) {
      return methods.init.apply(this,arguments);
    }else{
      $.error(method);
    }
  }

      $(document).mousemove(function( event ) {
$(imagezoomView.selector).css({
          'left': event.pageX,
          'top': event.pageY,
        });
});

// приделал код инициализации на время отладки

  $(document).ready(function(){
    $('[data-imagezoom]').imageZoom();
  });
})(jQuery);
  • Вопрос задан
  • 2344 просмотра
Пригласить эксперта
Ответы на вопрос 1
tennalian
@tennalian
$(document).on('mouseenter' - когда курсор на элементе срабатывает $('body').prepend('
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы