search
HomeWeb Front-endJS TutorialjQuery implements a simple image viewer_jquery

In the project, I DIYed a picture viewer. Because the initial code is not my own, I just changed it a little and it didn't turn out very well. I will rewrite the styles and encapsulation when I have time later, just accumulate them as backup. If there are children’s shoes that are useful, you can completely modify them on this basis. It is relatively easy and the code is relatively simple

The picture viewer has several main functions:

  1. Display pictures and picture information (picture name, publisher, etc.)

 2. Switch pictures

 3. Close the picture viewer

Initialization interface function pictureViewer.init: function(picInfos,tapNumber,isBig)

picInfos: 传入图片组信息,必须,格式如下
 var picInfos = [
  {
   "url" : "default.png",
   "data": [
   {
    "key":"名称:",
    "value":"测试图片"
   },
   {
    "key":"发布者:",
    "value":"chua"
   }
   ]
  },
  {
   "url" : "test.jpeg",
   "data": [
   {
    "key":"名称",
    "value":"测试图片"
   },
   {
    "key":"发布者:",
    "value":"发大水发大水发顺风h"
   },
   {
    "key":"这个图片的其他信息",
    "value":"vsfsgsdgfds234323424"
   }
   ]
  },
  ...
 ] //传入参数的样式 

tapNumber: The index of the picture to be displayed in the picture list, must start from 0
isBig: Whether to use large image for viewing, the default is false, optional
The html and css source codes are as follows (an example follows)

<!DOCTYPE html>
<html lang="ch-cn">
 <head>
  <meta charset="utf-8">
  <script type="text/javascript" src='jquery-1.9.1.js'></script>
 <link rel="stylesheet" type="text/css" href="imgTap.css">
 <script type="text/javascript" src='imgTap.js'></script>
 <style type="text/css">
 html,body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, button, textarea, p, blockquote, th, td{
  margin: 0;
  padding:0;
 }
 *{
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
 }

 body{
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
 }
 .imgTapDetail {
  display: none;
  position: absolute;
  z-index: 2000;
  top: 0;
  width: 100%;
  height: 100%;
  background: none transparent scroll repeat 0% 0%;
  color: #000 !important;
 }
 .page-secShadow {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
  background-color: rgba(0,0,0,.3);
  filter: alpha(opacity=50);
 }

 .page-shadowContent {
  width: 40%;
  margin: 0 auto;
  margin-top: 20%;
  position: relative !important;
  min-width: 400px;
 }
 .page-shadowContent.widget-big{

 }
 .leftTap, .rightTap {
  margin-top: 50%;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  position: absolute;
  top: -80px;
  cursor: pointer;
 }
 .leftTap {
  left: -30%;
  background: url("imgTap.png") 0 0 no-repeat;
 }
 .rightTap {
  right: -30%;
  background: url("imgTap.png") -80px 0 no-repeat;
 }
 .closeTap {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  position: absolute;
  right: -30px;
  top: -30px;
  cursor: pointer;
  background: url("imgTap.png") 0 -165px no-repeat;
  z-index: 99;
 }
 .widget {
  padding: 0 5px;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
  margin: 3px 0 10px 0;
 }
 .widget-body {
  background-color: #fff;
  -webkit-box-shadow: 1px 0 10px 1px rgba(0,0,0,.3);
  -moz-box-shadow: 1px 0 10px 1px rgba(0,0,0,.3);
  box-shadow: 1px 0 10px 1px rgba(0,0,0,.3);
  padding: 12px;
 }
 .page-shadowContent .widget-body {
  min-height: 200px;
  padding: 15px!important;
  border: 1px solid #ccc;
  overflow: hidden;
 }
 .widget-body .row {
  margin-right: -10px !important;
  margin-left: -10px !important;
 }
 .imgShow {
  text-align: center;
  height: 400px;
  padding-left: 10px;
  padding-right: 10px;
  /*background: url(default.png) center no-repeat;*/
 }
 #tapContent{
  padding-left: 10px;
  padding-right: 10px;
 }
 .imgContent {
  max-width: 400px;
  max-height: 400px;
  vertical-align: middle;
 }
 .widget-body img {
  max-width: 100%;
  height: auto!important;
 }
 .imgShow > span {
  height: 100%;
  display: inline-block;
  vertical-align: middle;
 } 
 .imgTapDetail .form-group {
  overflow: hidden;
  margin-bottom: 0 !important;
  position: relative;
  min-height: 34px;
 }
 .widget-detail .form-group .detail-LabelStyle {
  float: left;
  padding-left: 5px;
  /* max-width: 50%; */
  text-align: left;
  line-height: 34px!important;
  color: rgb(115, 115, 115);
  padding-right: 5px;
  height: 34px;
  overflow: hidden;
  left: 0;
  top: 0;
 }
 .widget-detail .form-group .detail-SpanStyle {
  padding: 8px 0 6px 5px;
  line-height: 20px;
  width: auto;
  height: auto!important;
  min-height: 34px;
  float: left;
  /* margin-left: 80px; */
  word-break: break-all;
 }
 .widget-big {
  width: 80%;
  min-width: 300px;
 }
 .widget-big .leftTap{
  left: -10%;
 }
 .widget-big .rightTap{
  right: -10%;
 }
 .widget-big .widget-detail{
  padding: 40px 0;
 }
 .widget-big .imgShow{
  min-height: 500px;
 }
 .widget-big .imgShow img{
  max-width: 800px; 
  max-height: 550px;
 }
 </style>
 </head>
 <body >
 <div class="imgTapDetail"></div>
 <script type="text/javascript">
 var picInfos = [
  {
  "url" : "default.png",
  "data": [
   {
   "key":"名称:",
   "value":"测试图片"
   },
   {
   "key":"发布者:",
   "value":"chua"
   }
  ]
  },
  {
  "url" : "test.jpeg",
  "data": [
   {
   "key":"名称",
   "value":"测试图片"
   },
   {
   "key":"发布者:",
   "value":"发大水发大水发顺风h"
   },
   {
   "key":"这个图片的其他信息",
   "value":"vsfsgsdgfds234323424"
   }
  ]
  }
 ] 
 pictureViewer.init(picInfos,0,true);
 </script> 
</html>

The source code of js is as follows

pictureViewer = {
 picInfos: [],
 curPicIndex: 0,
 isBig:false,//大图查看?默认为false。默认图片显示区域为window宽度的40%,大图为80%
 imgTapSelector:".imgTapDetail",
 init: function(picInfos,tapNumber,isBig){
  var _this = this;

  _this.picInfos = picInfos;
  _this.curPicIndex = tapNumber;
  _this.isBig = isBig;
  tapImgInit();
  
  //图片查看器初始化
  function tapImgInit(){
   //页面代码和事件只需要初始化一次即可
   if(!_this.guid){
    _this.guid = 1;
    initTapImgHtml();
    $(document).on("click","#rightTap",function(){
     _this.curPicIndex++;
     if(_this.curPicIndex == _this.picInfos.length){
      _this.curPicIndex = 0;
     }
     $("#tapContent").html("")
     tapImg()
    }).on("click","#leftTap",function(){
     _this.curPicIndex--;
     if(_this.curPicIndex < 0){
      _this.curPicIndex = _this.picInfos.length-1;
     }
     $("#tapContent").html("")
     tapImg();
    }).on("click","#closeTap",function(){
     $(_this.imgTapSelector).hide("fast")
    })
   }
   var offTop = top.document.body.scrollTop || top.document.documentElement.scrollTop;
   $('#imgTapPanel').css("margin-top",_this.isBig&#63;(offTop>30&#63;offTop:30):offTop + 100)
   tapImg();
   $(_this.imgTapSelector).show("fast");
  }
  //初始化图片查看器的html代码
  function initTapImgHtml(){
   var $detailText = '<div class="page-secShadow" >'
    + '<div id="imgTapPanel" class="page-shadowContent '+(_this.isBig&#63;"widget-big":"")+'">'
    + '<div id="leftTap" class="leftTap"></div>'
    + '<div id="rightTap" class="rightTap"></div>'
    + '<div id="closeTap" class="closeTap"></div>'
    + '<div class="widget row"><div class="widget-body">'
    + '<div class="widget-detail row">'
    + '<div class="imgShow">'
    + '<img  class="imgContent lazy"  src="/static/imghwm/default1.png"  data-src="logo.png"  id="tapImg" alt="jQuery implements a simple image viewer_jquery" ><span></span>'
    + '</div>'
    + '<div id="tapContent"></div>'
    + '</div></div></div></div></div>';  
   
   $(_this.imgTapSelector).html($detailText);
   hoverButton("#leftTap", 0, 0, 0, "-80px");
   hoverButton("#rightTap", "-80px", 0, "-80px", "-80px");
   hoverButton("#closeTap", 0, "-165px", "-60px", "-165px");
  }
  //添加左右切换图标、关闭图标的hover响应事件。这个其实可以起到css中更好一些
  function hoverButton(id, x, y, A, B){
   $(id).hover(function(){
    $(this).css('background-position', A + ' '+ B)
   },function(){
    $(this).css('background-position', x + ' '+ y)
   })
  }
  //刷新当前图片及图片信息
  function tapImg(){
   var reg = /[::]$/,
   leftTap = $("#leftTap"),
   rightTap = $("#rightTap"),
   imgTap = $("#tapImg"),
   contentTap = $("#tapContent");

   leftTap.css("display","block");
   rightTap.css("display","block");
   if(_this.picInfos.length == 1){
    leftTap.css("display","none");
    rightTap.css("display","none");
   }
   imgTap.attr("src",_this.picInfos[_this.curPicIndex].url);

   var data = _this.picInfos[_this.curPicIndex].data,
   dataLength = data.length,
   $text = "";

   for(var i=0; i<dataLength; i++){
    $text += '<div class="form-group">'
     + '<label class="detail-LabelStyle">'+data[i].key.replace(reg,"")+':</label>'
     + '<span id="spanLoginName" class="detail-SpanStyle">'+data[i].value+'</span>'
     + '</div>';
   };
   contentTap.empty().append($text);

   setTimeout(function(){
    if(_this.isBig && imgTap.height() > 400){
     imgTap.parent().attr("style","height:inherit");
    }else{
     imgTap.parent().removeAttr("style");
    }
   },1);
  }
 }
}

I hope this article will be helpful to everyone learning JavaScript programming.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software