/ Scripts & jquery / Заметки на изображении

Заметки на изображении

HIT

12.03.2017

1429

Помещаем на изображение заметки поясняющие ту или иную деталь. Данная функция может быть полезна для пояснения каких-либо чертежей или схем, выделения основных преимуществ товара и т.д.

Перебрал множество скриптов с подобным функционалом, но этот мне понравился больше других: выглядит довольно стильно, принцип работы прост.

Метки на изображении Points of Interest

Подключаем простой скрипт

jQuery(document).ready(function($){

//open interest point description
$('.cd-single-point').children('a').on('click', function(){
var selectedPoint = $(this).parent('li');
if( selectedPoint.hasClass('is-open') ) {
selectedPoint.removeClass('is-open').addClass('visited');
} else {
selectedPoint.addClass('is-open').siblings('.cd-single-point.is-open').removeClass('is-open').addClass('visited');
}
});

//close interest point description
$('.cd-close-info').on('click', function(event){
event.preventDefault();
$(this).parents('.cd-single-point').eq(0).removeClass('is-open').addClass('visited');
});

});

Подключаем стили — см. закладку стили (слева) + прописываем расположение меток

/* Расположение меток */

.cd-single-point:nth-of-type(1) {bottom: 40%; right: 30%;}

.cd-single-point:nth-of-type(2) {bottom: 24%; right: 46%;}

.cd-single-point:nth-of-type(3) {top: 28%; left: 20%;}

.cd-single-point:nth-of-type(4) {top: 20%; right: 22%;}

Верстка должна выглядеть следующим образом:

<div class="cd-product-wrapper">
<img src="/wp-content/uploads/2017/03/Lost_Planet_3-700x298.jpg">
<ul>

<li class="cd-single-point">
<a class="cd-img-replace" href="#0"></a>
<div class="cd-more-info cd-bottom">
<h2>Заголовок</h2>
<p>Описание</p>
<a href="#0" class="cd-close-info cd-img-replace">Close</a>
</div>
</li>

<!-- следующая метка -->

</ul>
</div>

Дополнительный класс для cd-more-info это 4 направления открытия метки: cd-top (вверх), cd-bottom (вниз), cd-left (влево), cd-right (вправо)

  • Title here

    Description here

    Close
  • Title here

    Description 2 here

    Close

Заметки на изображении от Adama Grayson

Нашел еще одно неплохое решение, но с другой реализацией, в данном случае упор делается больше на скрипт и эффект действует при наведении.

Верстка состоит из одного div’а с классом spot-container.

Данный скрипт чувствителен к месту расположения spot-container. Сбивают расположение всплывающих окон родительские свойства margin и float: left;

CSS

.spot-container {
  width: 100%;
  height: 500px;
  position: relative;
  background-image: url(/wp-content/uploads/2017/03/black-and-white-nature-photography-stag.jpg);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
  
.hot-spot {
  width: 20px;
  height: 20px;
  background-color: #D29A4E;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
  opacity: 0.8;
  z-index: 1;
}
		  
.hot-spot:after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 2px solid #D29A4E;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    opacity: 0;
    transition: 0.2s all;
}			
				
.hot-spot:hover {cursor: pointer; opacity: 1;}

.hot-spot:hover:after {width: 25px; height: 25px; opacity: 1;}
						  
.speech-bubble {
  position: absolute;
  width: 150px;
  background-color: white;
  border-radius: 4px;
  text-align: center;
  display: none;
  z-index: 2;
}
						  
.speech-bubble h1 {font-size: 20px; margin-top: 12px; color: #333333;}
							  
.speech-bubble p {
    margin-top: 4px;
    margin-bottom: 12px;
    font-style: italic;
    color: #888888;
}
								  
.speech-bubble p:after {
    top: 100%;
    left: 50%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-color: rgba(255, 255, 255, 0);
    border-top-color: #ffffff;
    border-width: 10px;
    margin-left: -10px;
}

В данном скрипте х=0, y=0 — это центр изображения (размер изображения также задается здесь — imageWidth, imageHeight)

var imageWidth = 737,
    imageHeight = 500,
    imageAspectRatio = imageWidth / imageHeight,
    $window = $(window);

var hotSpots = [{
  'title': 'Mouth',
  'description': 'scream.',
  'x': 50,
  'y': 50
}, {
  'title': 'Body',
  'description': 'Look at it.',
  'x': 100,
  'y': 100
}, {
  'title': 'Antlers',
  'description': 'They crazy.',
  'x': -50,
  'y': -50
}, {
  'title': 'This Ear',
  'description': 'It can hear things.',
  'x': -125,
  'y': 125
}];

function appendHotSpots() {
  for (var i = 0; i < hotSpots.length; i++) {
    var $hotSpot = $('<div>').addClass('hot-spot');
    $('.spot-container').append($hotSpot);
  }
  positionHotSpots();
}

function appendSpeechBubble() {
  var $speechBubble = $('<div>').addClass('speech-bubble');
  $('.spot-container').append($speechBubble);
}

function handleHotSpotMouseover(e) {
  var $currentHotSpot = $(e.currentTarget),
      currentIndex = $currentHotSpot.index(),
      $speechBubble = $('.speech-bubble'),
      title = hotSpots[currentIndex]['title'],
      description = hotSpots[currentIndex]['description'],
      hotSpotTop = $currentHotSpot.offset().top,
      hotSpotLeft = $currentHotSpot.offset().left,
      hotSpotHalfSize = $currentHotSpot.width() / 2,
      speechBubbleHalfSize = $speechBubble.width() / 2,
      topTarget = hotSpotTop - $speechBubble.height(),
      leftTarget = (hotSpotLeft - (speechBubbleHalfSize)) + hotSpotHalfSize;
  
  $speechBubble.empty();
  $speechBubble.append($('<h1>').text(title));
  $speechBubble.append($('<p>').text(description));
  
  $speechBubble.css({
    'top': topTarget - 20,
    'left': leftTarget,
    'display': 'block'
  }).stop().animate({
    opacity: 1
  }, 200);
}

function handleHotSpotMouseout(){
  var $speechBubble = $('.speech-bubble');
  $speechBubble.stop().animate({
    opacity: 0
  }, 200, function(){
    $speechBubble.hide();
  });
}

function positionHotSpots() {
  var windowWidth = $window.width(),
    windowHeight = $window.height(),
    windowAspectRatio = windowWidth / windowHeight,
    $hotSpot = $('.hot-spot');

  $hotSpot.each(function(index) {
    var xPos = hotSpots[index]['x'],
        yPos = hotSpots[index]['y'],
        desiredLeft = 0,
        desiredTop = 0;

    if (windowAspectRatio > imageAspectRatio) {
      yPos = (yPos / imageHeight) * 100;
      xPos = (xPos / imageWidth) * 100;
    } else {
      yPos = ((yPos / (windowAspectRatio / imageAspectRatio)) / imageHeight) * 100;
      xPos = ((xPos / (windowAspectRatio / imageAspectRatio)) / imageWidth) * 100;
    }

    $(this).css({
      'margin-top': yPos + '%',
      'margin-left': xPos + '%'
    });

  });
}

appendHotSpots();
appendSpeechBubble();
$(window).resize(positionHotSpots);
$('.hot-spot').on('mouseover', handleHotSpotMouseover);
$('.hot-spot').on('mouseout', handleHotSpotMouseout);

Пример (скорее всего сами всплывающие подсказки не будут видны, из-за некоторых родительских свойств)

 

Поделиться в соц. сетях:

  • Комментарии
  • Вложения

Добавить комментарий

Пока нет комментариев. Будь первым!

Заметки на изображении Заметки на изображении Заметки на изображении
Фильтр по наличию
Рекомендации для васФильтр по наличиюOpttour.ru
Спасибо! Наш менеджер свяжется с Вами в течении 5 минут.