Найти и продублировать изображение с помощью JQuery - PullRequest
1 голос
/ 02 марта 2010

Я пытаюсь использовать JQuery для создания динамического заголовка страницы, используя изображение, которое существует в статье. Я планирую дать изображению класс (.thumbnail). Я хочу удалить изображение из статьи, как только оно будет использовано для заголовка. Вот логика:

  • Найти тег IMG с помощью класса .thumbnail
  • Переместите это изображение в новый DIV (#dynHeader), классифицируйте его .Image1
  • Масштабировать изображение до x пикселей в высоту, сохранять формат по ширине
  • Найти ширину вновь масштабированного изображения (var stayWidth)
  • Рассчитать оставшуюся ширину # dynHeader
  • Дублируйте IMG справа от .Image1, назовите его .Image2
  • Установить его ширину равной значению stayWidth
  • Обрезать его до высоты .Image1
  • Поместите его на ось Y с конкретным значением

Мне нужно знать, как найти и продублировать IMG .thumbnail. Я уверен, что больше проблем возникнет, когда я продолжу работать над этим, но я полностью застрял. Я думаю об этом неправильно? Есть ли способ разместить одно и то же изображение на странице дважды?

Спасибо за любую помощь.

1027 * для -Alex- *

Редактировать: Я публикую решение, так как использую его на своем сайте для всех, кто может столкнуться с этой проблемой. Взял код из ответа и настроил его для правильной работы.

 //need to clone before removing class so that the original is deletable later.
    var cache = $('img.thumbnail').clone().removeClass('thumbnail').addClass('Image1').css('float','left');
//remove the original from the text         
            $('img.thumbnail').remove();
//attach the cloned image to the header
            $('#dynHeader').append(cache);
//find the ratio
            var ratio = (cache.width() / cache.height());
//set variable to hold image height
            var imageHeight = (365);
//set variable to hold image width 
            var imageWidth = (imageHeight*ratio);
//set the image height & width
            cache.height(imageHeight).width(imageWidth);
//figure the amount of width remaining in the header
            var remainWidth = $('#dynHeader').width() - imageWidth;
//clone the header image
            var dupe = cache.clone();
//work with the cloned image - change the class to Image2, set the width and height         dupe.removeClass('Image1').addClass('Image2').css("width",remainWidth+"px").css("height","auto");
//place Image2 to the right of Image1
            cache.after(dupe);

Затем я использовал CSS для позиционирования Image2 и скрытия переполнения (эффект масштабирования и кадрирования, для которого я снимал).

#dynHeader{
    height: 365px;
    overflow: hidden;
    margin-bottom: 30px;
}
img.Image2{
    position: relative;
    top: -150px;
}

Надеюсь, это поможет кому-то еще! Спасибо Алекс за правильное указание.

1 Ответ

4 голосов
/ 02 марта 2010

Это должно помочь вам начать: (пожалуйста, имейте в виду, что это 100% от макушки моей головы и уже поздно ... здесь могут быть некоторые опечатки!)

//Find IMG tag with .thumbnail class:
$('img.thumbnail')

//Move that image to a new DIV (#dynHeader), class it .Image1

// change class before and then grab image
var cache = $('img.thumbnail').removeClass('thumbnail').addClass('Image1').clone();

// remove from context
$('img.thumbnail').remove();

// add it to the div
$('#dynHeader').append(cache);

// Scale the image to x pixels in height, maintain aspect for width
// cache selector
var cache = $('.Image1');

// calculate aspect
var ratio = (cache.width() / cache.height());

// calculate & store width
var remainWidth = (x*ratio);

// scale to x pixels in height
cache.height(x).width(remainWidth);

// Calculate the remaining width of #dynHeader
var remainHeaderWidth = $('#dynHeader').width() - remainWidth;

// Duplicate the IMG to the right of .Image1, call it .Image2
// assuming you mean "duplicate it and add to the right"
var dupe = cache.clone();
dupe.removeClass('Image1).addClass('Image2');

// Set its width to the value of remainWidth
dupe.width(remainHeaderWidth);

// Crop it to the height of .Image1
// not sure about the cropping, here's how you would change it without maintaing aspect
dupe.height(cache.height());

// add it after the first image
cache.after(dupe);

// Position it on the Y axis with a specific value
// cant remember off the top of my head but as far as I know you have to first find its    
// position on the axis and then shift it maybe applying relative css positioning

Это, безусловно, может быть улучшено, но должно дать вам общее представление:)

Да, и если вы разместите одно и то же изображение на странице, нет проблем, просто клонируйте () элемент и добавляйте его туда, куда хотите столько раз, сколько захотите!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...