Конкретные продукты JD или Taobao имеют эффект увеличительного стекла. Хотя в Интернете есть много подобных плагинов, при применении их к проектам есть много неудобств. Мне потребовалось некоторое время, чтобы написать аналогичный плагин и накопленный код. Почему бы не сделать это !! давай:
Я планирую инкапсулировать этот специальный эффект в плагин, сначала реализуйте самый базовый алгоритм, а затем инкапсуляю его шаг за шагом:
Окончательный эффект:
HTML -код:
Кода -копия выглядит следующим образом:
<div id = "Magnifier"> </div>
CSS -код:
Кода -копия выглядит следующим образом:
<style>
* {
поля: 0;
Заполнение: 0;
}
</style>
Кажется, что ничего нет, давайте начнем с нашего мощного путешествия JS:
код JavaScript:
Кода -копия выглядит следующим образом:
Функция CreateElement (Magnifierid, Simg, Bimg) {
var Maginifier = $ (MAGNIFIERID);
MAGNIFIER.STYLE.POSITION = 'Относительный';
// Маленькая картина Div
var smalldiv = $ create ("div");
smalldiv.setattribute ("id", "small");
smalldiv.style.position = "Absolute";
// маска слой
var mask = $ create ("div");
mask.setattribute ("id", "mask");
mask.style.position = "Absolute";
// объектив
var mirror = $ create ("div");
mirror.setattribute ("id", "Mirror");
mirror.style.opacity = 0,3;
mirror.style.position = "Absolute";
mirror.style.display = "none";
// маленькая картина
var smallimg = $ create ("img");
shipimg.setattribute ("src", simg);
shipimg.setattribute ("id", "shinkimg");
shineimg.onload = function () {
// Если высота или ширина увеличительного стекла не установлены, установите размер увеличительного стекла в соответствии с размером маленькой картины
if (! MAGNIFIER.OFFSETHEITH) {
MAGNIFIER.STYLE.Width = this.OffSetWidth+"px";
MAGNIFIER.STYLE.HEITH = this.Offsetheight + "px";
}
// размер слоя маски такой же, как и маленькая картина
mask.style.opacity = "0";
mask.style.width = this.width + 'px';
mask.style.height = this.height + "px";
mask.style.zindex = 2;
bigdiv.style.left = this.width + 5 + "px";
bigdiv.style.top = "-5px";
}
SmallDiv.AppendChild (маска);
SmallDiv.AppendChild (зеркало);
SmallDiv.AppendChild (shinkimg);
// окна
var bigdiv = $ create ("div");
bigdiv.setattribute ("id", "big");
bigdiv.style.position = "Absolute";
bigdiv.style.overflow = "hidden";
bigdiv.style.display = "none";
var bigimg = $ create ("img");
bigimg.setattribute ("src", bimg);
bigimg.setattribute ("id", "Bigimg");
bigimg.style.position = "Absolute";
bigdiv.appendchild (Bigimg);
MAGNIFIER.AppendChild (SmallDiv);
MAGNIFIER.AppendChild (bigdiv);
}
Функция SetMagnifiersTyle (Mirrorstyle, Shichangstyle) {
//зеркало
для (var item in mirrorstyle) {
mirror.style [item] = mirrorstyle [item];
}
для (var item в shichangstyle) {
$ ("Big"). Style [item] = shichangstyle [item];
}
}
function RegisterEvent () {
$ ("Маска"). onmouseover = function () {
$ ("big"). style.display = "block";
mirror.style.display = "block";
}
$ ("Маска"). onmouseout = function () {
$ ("big"). style.display = "нет";
mirror.style.display = "none";
}
$ ("маска"). onmouseMove = function (evt) {
var oevent = evt || событие;
var disx = oevent.offsetx;
var disy = oevent.offsety;
var mirrorleft = disx - mirror.offsetwidth / 2;
var mirrortop = disy - mirror.offsetheight / 2;
if (mirrorleft <0) {
mirrorleft = 0;
}
иначе if (mirrorleft> mask.offsetwidth - mirror.offsetwidth) {
mirrorleft = mask.offsetwidth - mirror.offsetwidth;
}
if (mirrortop <0) {
mirrortop = 0;
}
иначе if (mirrortop> mask.offsetheight - mirror.offsetheight) {
mirrortop = mask.offsetheight - mirror.offsetheight;
}
mirror.style.top = mirrortop + "px";
mirror.style.left = mirrorleft + "px";
var pax = mirrortop / (mask.offsetheight - mirror.offsetheight);
var pay = mirrorleft / (mask.offsetwidth - mirror.offsetwidth);
$ ("bigimg"). style.top = -pax * ($ ("Bigimg"). Offsetheight - $ ("Big"). Offsetheight) + "px";
$ ("bigimg"). style.left = -pay * ($ ("Bigimg"). OffsetWidth - $ ("Big"). OffsetWidth) + "px";
}
}
Функция $ (id) {
return document.getElementbyId (id);
}
функция $ create (type) {
return document.createElement (type);
}
Наконец, давайте назовем это нагрузкой:
Кода -копия выглядит следующим образом:
window.onload = function () {
CreateElement («Magnifier», «Images/Magnifier/small.jpg», «Image/Magnifier/Big.jpg»);
SetMagnifiersTyle ({"ширина": "30px", "height": "30px", "founalcolor": "#ffff"}, {"ширина": "250px", "height": "250px"});
RegisterEvent ();
}
Эффект наконец -то был рассчитан.
2. Давайте инкапсулируем это дальше:
Код класса Magnifer:
Кода -копия выглядит следующим образом:
функциональное увеличение (
MAGNIFIERID, // идентификатор контейнера увеличения
SIMG, // Маленькая картина SRC
bimg, // большая картина src
Зеркальный стиль, // стиль объектива в маленькой картине, данные формата JSON
ViewStyle // Предварительный просмотр стиля окна, данные формата JSON
) {
var _this = это;
this.magnifiercontainer = null; //Контейнер
this.smalldiv = null; // небольшой контейнер изображения
this.mask = null; // Маленький слой маски изображения
this.mirror = null; // Маленькая картинка
this.smallimg = null; // маленькая картина
this.bigdiv = null; // Предварительный просмотр
this.bigimg = null; // большое изображение
var init = function () {
_This.magnifierContainer = _this. $ (MAGNIFIERID);
_This.createElement (simg, bimg);
_This.SetMagnifiersTyle (зеркальный стиль, ViewStyle);
_this.mainevent ();
}
init ();
}
Magnifier.prototype.createElement = function (simg, bimg) {
var _this = это;
var $ create = this. $ create;
this.magnifiercontainer.style.position = 'относительный'; // далеко от потока документов и изменить его по мере необходимости
this.smalldiv = $ create ("div");
this.smalldiv.setattribute ("id", "small");
this.smalldiv.style.position = "Absolute";
this.mask = $ create ("div");
this.mask.setattribute ("id", "mask");
this.mask.style.position = "Absolute";
this.mirror = $ create ("div");
this.mirror.setattribute ("id", "Mirror");
this.mirror.style.opacity = 0,3;
this.mirror.style.position = "Absolute";
this.mirror.style.display = "нет";
this.smallimg = $ create ("img");
this.smallimg.setattribute ("src", simg);
this.smallimg.setattribute ("id", "smallimg");
this.smallimg.onload = function () {
// Если высота или ширина увеличительного стекла не установлены, установите размер увеличительного стекла в соответствии с размером маленькой картины
if (! _This.magnifierContainer.offsetheight) {
_This.magnifierContainer.style.width = this.offsetWidth + "px";
_This.magnifierContainer.style.height = this.offsetheight + "px";
}
// размер слоя маски такой же, как и маленькая картина
_this.mask.style.opacity = "0";
_this.mask.style.width = this.offsetwidth + 'px';
_This.mask.style.height = this.offsetheight + "px";
_This.mask.style.zindex = 2;
_This.bigdiv.style.left = this.OffSetWidth + 5 + "px";
_This.bigdiv.style.top = "-5px";
}
this.smalldiv.appendchild (this.mask);
this.smalldiv.appendchild (this.mirror);
this.smalldiv.appendchild (this.smallimg);
this.bigdiv = $ create ("div");
this.bigdiv.setattribute ("id", "big");
this.bigdiv.style.position = "Absolute";
this.bigdiv.style.overflow = "hidden";
this.bigdiv.style.display = "none";
this.bigimg = $ create ("img");
this.bigimg.setattribute ("src", bimg);
this.bigimg.setattribute ("id", "Bigimg");
this.bigimg.style.position = "Absolute";
this.bigdiv.appendchild (this.bigimg);
this.magnifiercontainer.appendchild (this.smalldiv);
this.magnifiercontainer.appendchild (this.bigdiv);
}
MAGNIFIER.Prototype.SetMagnifiersTyle = function (MirrorStyle, ViewStyle) {
для (var item in mirrorstyle) {
this.mirror.style [item] = mirrorstyle [item];
}
Удалить пункт;
для (var item in view -style) {
this.bigdiv.style [item] = viewstyle [item];
}
}
Magnifier.prototype.mainevent = function () {
var _this = это;
this.mask.onmouseover = function () {
_This.bigdiv.style.display = "block";
_This.mirror.style.display = "block";
}
this.mask.onmouseout = function () {
_This.bigdiv.style.display = "none";
_This.mirror.style.display = "none";
}
this.mask.onmousemove = function (evt) {
var oevent = evt || событие;
var disx = oevent.offsetx || oevent.layerx; // FF совместим
var disy = oevent.offsety || oevent.layery;
var mirrorleft = disx - _this.mirror.offsetwidth / 2;
var mirrortop = disy - _this.mirror.offsetheight / 2;
if (mirrorleft <0) {
mirrorleft = 0;
}
else if (mirrorleft> this.offsetwidth - _this.mirror.offsetwidth) {
mirrorleft = this.offsetwidth - mirror.offsetwidth;
}
if (mirrortop <0) {
mirrortop = 0;
}
else if (mirrortop> this.offsetheight - _this.mirror.offsetheight) {
mirrortop = this.offsetheight - _this.mirror.offsetheight;
}
_this.mirror.style.top = mirrortop + "px";
_This.mirror.style.left = mirrorleft + "px";
var pax = mirrortop / (this.offsetheight - _this.mirror.offsetheight);
var pay = mirrorleft / (this.offsetwidth - _this.mirror.offsetwidth);
_This.bigimg.style.top = -pax * (_this.bigimg.offsetheight - _this.bigdiv.offsetheight) + "px";
_This.bigimg.style.left = -pay * (_This.bigimg.offsetWidth - _This.bigdiv.offsetWidth) + "px";
}
}
Magnifier.prototype. $ = Function (id) {
return document.getElementbyId (id);
}
Magnifier.prototype. $ Create = function (type) {
return document.createElement (type);
}
Наконец, под вызовом Onload:
Кода -копия выглядит следующим образом:
window.onload = function () {
Новое увеличение (
«Великолепный»,
"Images/Magnifier/small.jpg",
"Images/Magnifier/big.jpg",
{"ширина": "30px", "height": "30px", "founalcolor": "#ffff"},
{"Ширина": "250px", "Высота": "250px"}
);
}
Приведенное выше контент, описанный в этой статье, надеюсь, вам понравится.