建站资源下载详情
为您免费提供多种建站资源下载,包括网站模板下载、前端插件下载和字体下载!您只需注册为会员即可任意下载!

GLightbox 优雅而强大的纯JS任意内容库灯箱插件

来源:易助科技网浏览量:58收藏

简介


GLightbox是一个简单而强大的、移动友好的图库lightbox插件,使用纯JavaScript和CSS/CS3编写。


更多灯箱画廊插件:👉  [ 详情 ]


GLightbox插件官网首页截图


插件特定


轻量级 —— 仅11KB Gzipped

快速响应 —— 适用于任何屏幕尺寸

画廊支持 —— 创建多个画廊

响应图像支持 —— 让浏览器使用当前屏幕分辨率的最佳图像

视频支持 —— Youtube、Vimeo和自动播放的自托管视频

内联内容支持 —— 显示任何内联内容

Iframe支持 —— 是否需要嵌入Iframe?没问题

键盘导航 —— esc、箭头键、制表符和回车键都是您所需要的

触摸导航 —— 移动触摸事件

可缩放图像 —— 在移动设备和桌面上缩放和拖动图像

API —— 使用提供的方法控制灯箱


浏览器支持情况


Safari
Mobile Safari
Opera
Edge
Firefox
Internet Explorer 11



使用


1.  引入


安装


$ npm install glightbox
# OR
$ yarn add glightbox
# OR
$ bower install glightbox

// Using ESM specification
import '/path/to/glightbox.js';

// Using a bundler like webpack
import GLightbox from 'glightbox';


html中引入文件


<link rel="stylesheet" href="dist/css/glightbox.css" />
<script src="dist/js/glightbox.min.js"></script>

<!-- USING A CDN -->

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/glightbox/dist/css/glightbox.min.css" />
<script src="https://cdn.jsdelivr.net/gh/mcstudios/glightbox/dist/js/glightbox.min.js"></script>

<script type="text/javascript">
  const lightbox = GLightbox({ ...options });
</script>

<!-- USING ES MODULES -->

<script type="module">
  import 'https://cdn.jsdelivr.net/gh/mcstudios/glightbox/dist/js/glightbox.min.js';

  const lightbox = GLightbox({ ...options });
</script>



2.  HTML


使用“href”属性指定要加载到库灯箱中的内容。请注意,分组的媒体内容必须具有相同的类。


<!-- Simple image -->
<a href="large.jpg" class="glightbox">
  <img src="small.jpg" alt="image" />
</a>

<!-- Video -->
<a href="https://vimeo.com/115041822" class="glightbox2">
  <img src="small.jpg" alt="image" />
</a>

<!-- Gallery -->
<a href="large.jpg" class="glightbox3" data-gallery="gallery1">
  <img src="small.jpg" alt="image" />
</a>
<a href="video.mp4" class="glightbox3" data-gallery="gallery1">
  <img src="small.jpg" alt="image" />
</a>

<!-- Simple Description -->
<a href="large.jpg" class="glightbox4" data-glightbox="title: My title; description: this is the slide description">
  <img src="small.jpg" alt="image" />
</a>

<!-- Advanced Description -->
<a href="large.jpg" class="glightbox5" data-glightbox="title: My title; description: .custom-desc1">
  <img src="small.jpg" alt="image" />
</a>

<div class="glightbox-desc custom-desc1">
  <p>The content of this div will be used as the slide description</p>
  <p>You can add links and any HTML you want</p>
</div>

<!-- URL with no extension -->
<a href="https://picsum.photos/1200/800" data-glightbox="type: image">
  <img src="small.jpg" alt="image" />
</a>
<!-- OR using multiple data attributes -->
<a href="https://picsum.photos/1200/800" data-type="image">
  <img src="small.jpg" alt="image" />
</a>

<!-- Using responsive images: specify sizes and srcset through data attributes in the
     same way you would with the img tag.
     See: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images -->
<a href="deafult.jpg" class="glightbox6" data-title="Responsive example"
data-description="Your browser will choose the optimal image for the resolution"
data-sizes="(max-width: 600px) 480px, 800px"
data-srcset="img480.jpg 480w, img800.jpg 800w">
  <img src="small.jpg" alt="image" />
</a>



3. 配置项


1)Slide 配置项


您可以为每张幻灯片指定一些配置项,可用配置项包括:


title
alt
description
descPosition
type
effect
width
height
zoomable
draggable


<!-- One line config -->
<a href="large.jpg" data-glightbox="title: Your title; description: description here; descPosition: left; type: image; effect: fade; width: 900px; height: auto; zoomable: true; draggable: true;"></a>

<!-- Multiple data attributes / You can use the options as separated data attributes -->
<a
  href="large.jpg"
  data-title="My title"
  data-description="description here"
  data-desc-position="right"
  data-type="image"
  data-effect="fade"
  data-width="900px"
  data-height="auto"
  data-zoomable="true"
  data-draggable="true"
></a>



2)Lightbox 配置项


const lightbox = GLightbox({
    touchNavigation: true,
    loop: true,
    autoplayVideos: true
});

// Instead of using a selector, define the gallery elements
const myGallery = GLightbox({
    elements: [
        {
            'href': 'https://picsum.photos/1200/800',
            'type': 'image',
            'title': 'My Title',
            'description': 'Example',
        },
        {
            'href': 'https://picsum.photos/1200/800',
            'type': 'image',
            'alt': 'image text alternatives'
        },
        {
            'href': 'https://www.youtube.com/watch?v=Ga6RYejo6Hk',
            'type': 'video',
            'source': 'youtube', //vimeo, youtube or local
            'width': 900,
        },
        {
            'content': '<p>This will append some html inside the slide</p>' // read more in the API section
        },
        {
            'content': document.getElementById('inline-example') // this will append a node inside the slide
        },
    ],
    autoplayVideos: true,
});
myGallery.open();

// If later you need to modify the elements you can use setElements
myGallery.setElements([...]);



3)全部配置项


OptionTypeDefaultDescription
selectorstring.glightbox选择器的名称,例如“.glightbox”、“data glightbox”或“*[data glightbox]”
elementsarraynull您可以传递库中所需的所有项目,而不是传递选择器。
skinstringclean皮肤的名称,它将向灯箱添加一个类,以便您可以使用css对其进行样式设置。
openEffectstringzoom灯箱打开时效果的名称。 (zoom, fade, none)
closeEffectstringzoom灯箱关闭时效果的名称。(zoom, fade, none)
slideEffectstringslide幻灯片更改效果的名称。 (slide, fade, zoom, none)
moreTextstringSee more有关移动设备上描述的更多文本。
moreLengthnumber60添加moreText链接之前在描述上显示的字符数(仅适用于手机),如果为0,则显示整个描述。
closeButtonbooleantrue显示或隐藏关闭按钮。
touchNavigationbooleantrue启用或禁用触摸导航 (swipe).
touchFollowAxisbooleantrue在移动设备上拖动时,图像跟随轴。
keyboardNavigationbooleantrue启用或禁用键盘导航。
closeOnOutsideClickbooleantrue在活动幻灯片外部单击时关闭灯箱。
startAtnumber0在定义的索引处启动灯箱。
widthnumber900px内联元素和iframe的默认宽度,您可以在每张幻灯片上定义特定的大小。您可以使用任何单位,例如全宽为90%或100vw。
heightnumber506px内联元素和iframe的默认高度,您可以在每张幻灯片上定义特定的大小。您可以使用任何单位,例如90%或100vh。对于内联元素,您可以将高度设置为自动。
videosWidthnumber960px视频的默认宽度。视频具有响应性,因此不需要高度。宽度可以是px、%甚至vw,例如,对于全宽视频,可以是500px、90%或100vw
descPositionstringbottom幻灯片描述的全局位置,您可以在每张幻灯片上定义特定位置(bottom, top, left, right).
loopbooleanfalse循环滑动结束。
zoomablebooleantrue启用或禁用可缩放图像—您也可以在单个节点上使用data-zoomable=“false”。
draggablebooleantrue启用或禁用鼠标拖动以转到上一张和下一张幻灯片(仅限图像和内联内容),您也可以在各个节点上使用data-draggable=“false”。
dragToleranceXnumber40与draggable一起使用。用户必须拖动才能转到上一张或下一张幻灯片的像素数。
dragToleranceYnumber65与draggable一起使用。用户必须向上或向下拖动才能关闭灯箱的像素数(设置0可禁用垂直拖动)。
dragAutoSnapbooleanfalse如果为true,则幻灯片将自动更改为上一页/下一页,或者如果达到dragToleranceX或dragTolenanceY,则关闭幻灯片,否则将等待鼠标释放。
preloadbooleantrue启用或禁用预加载。
svgobject{}设置你自己的svg图标。
cssEfectsobject'See animations'定义或调整灯箱动画。请参阅README文件中的动画部分。
lightboxHTMLstring'See themes'您可以完全更改GLightbox的html。请参阅README文件中的主题部分。
slideHTMLstring'See themes'您可以完全更改单个幻灯片的html。请参阅README文件中的主题部分。
autoplayVideosbooleantrue打开时自动播放视频。
autofocusVideosbooleanfalse如果真正的视频将集中在播放上,以允许播放器的键盘排序,这将停用上一个和下一个箭头来更改幻灯片,所以只有当你知道自己在做什么时才使用它。
plyrobject{}View video player options.



4. 事件


您可以使用GLightbox实例侦听事件(请参阅表下的示例)。您可以使用on()API方法或once()。


const lightbox = GLightbox();
lightbox.on('open', () => {
  // Do something
});

lightbox.once('slide_changed', () => {
  // Do something just one time
});


更多事件


Event Type	Description
open	Provide a function when the lightbox is opened.
close	Provide a function when the lightbox is closed.
slide_before_change	Trigger a function before the slide is changed.
slide_changed	Trigger a function after the slide is changed.
slide_before_load	Trigger a function before a slide is loaded for the first time, the function will only be called once
slide_after_load	Trigger a function after a slide is loaded and it's content is set for the first time, the function will only be called once
slide_inserted	Trigger a function after a slide is inserted using insertSlide.
slide_removed	Trigger a function after a slide is removed`


示例


const lightbox = GLightbox();
lightbox.on('slide_before_change', ({ prev, current }) => {
  console.log('Prev slide', prev);
  console.log('Current slide', current);

  // Prev and current are objects that contain the following data
  const { slideIndex, slideNode, slideConfig, player, trigger } = current;

  // slideIndex - the slide index
  // slideNode - the node you can modify
  // slideConfig - will contain the configuration of the slide like title, description, etc.
  // player - the slide player if it exists otherwise will return false
  // trigger - this will contain the element that triggers this slide, this can be a link, a button, etc in your HTML, it can be null if the elements in the gallery were set dinamically
});

lightbox.on('slide_changed', ({ prev, current }) => {
  console.log('Prev slide', prev);
  console.log('Current slide', current);

  // Prev and current are objects that contain the following data
  const { slideIndex, slideNode, slideConfig, player, trigger } = current;

  // slideIndex - the slide index
  // slideNode - the node you can modify
  // slideConfig - will contain the configuration of the slide like title, description, etc.
  // player - the slide player if it exists otherwise will return false
  // trigger - this will contain the element that triggers this slide, this can be a link, a button, etc in your HTML, it can be null if the elements in the gallery were set dinamically

  if (player) {
    if (!player.ready) {
      // If player is not ready
      player.on('ready', (event) => {
        // Do something when video is ready
      });
    }

    player.on('play', (event) => {
      console.log('Started play');
    });

    player.on('volumechange', (event) => {
      console.log('Volume change');
    });

    player.on('ended', (event) => {
      console.log('Video ended');
    });
  }
});

// Useful to modify the slide
// before it's content is added
lightbox.on('slide_before_load', (data) => {
  // data is an object that contain the following
  const { slideIndex, slideNode, slideConfig, player, trigger } = data;

  // slideIndex - the slide index
  // slideNode - the node you can modify
  // slideConfig - will contain the configuration of the slide like title, description, etc.
  // player - the slide player if it exists otherwise will return false
  // trigger - this will contain the element that triggers this slide, this can be a link, a button, etc in your HTML, it can be null if the elements in the gallery were set dinamically
});

// Useful to execute scripts that depends
// on the slide to be ready with all it's content
// and already has a height
// data will contain all the info about the slide
lightbox.on('slide_after_load', (data) => {
  // data is an object that contain the following
  const { slideIndex, slideNode, slideConfig, player, trigger } = data;

  // slideIndex - the slide index
  // slideNode - the node you can modify
  // slideConfig - will contain the configuration of the slide like title, description, etc.
  // player - the slide player if it exists otherwise will return false
  // trigger - this will contain the element that triggers this slide, this can be a link, a button, etc in your HTML, it can be null if the elements in the gallery were set dinamically
});

// Trigger a function when a slide is inserted
lightbox.on('slide_inserted', (data) => {
  // data is an object that contain the following
  const { slideIndex, slideNode, slideConfig, player, trigger } = data;

  // slideIndex - the slide index
  // slideNode - the node you can modify
  // slideConfig - will contain the configuration of the slide like title, description, etc.
  // player - the slide player if it exists otherwise will return false
  // trigger - null
});

// Trigger a function when a slide is removed
lightbox.on('slide_removed', (index) => {
  // index is the position of the element in the gallery
});



5. 视频播放


GLightbox包括 [ Plyer ] -最好的player,你可以将任何Plyer选项传递给player,在这里查看所有可用的 [ Plyer选项 ]。GLightbox只会在需要时插入播放器库,并且只有在打开lightbox时才会插入。

Internet Explorer 11。如果你需要对这个浏览器的支持,你需要设置js url以使用polyfilled版本。这不是默认的,因为IE11是古老的,我们需要让它消亡。


移动/平板电脑自动播放


请注意,自动播放在某些浏览器中被阻止,我们无法改变这一点。不幸的是,浏览器将决定是否可以自动播放您的视频。根据一些规则决定视频是否可以自动播放:


plyr: {
    js: 'https://cdn.plyr.io/3.6.2/plyr.polyfilled.js',
    ....


const lightbox = GLightbox({
  plyr: {
    css: 'https://cdn.plyr.io/3.5.6/plyr.css', // Default not required to include
    js: 'https://cdn.plyr.io/3.5.6/plyr.js', // Default not required to include
    config: {
      ratio: '16:9', // or '4:3'
      muted: false,
      hideControls: true,
      youtube: {
        noCookie: true,
        rel: 0,
        showinfo: 0,
        iv_load_policy: 3
      },
      vimeo: {
        byline: false,
        portrait: false,
        title: false,
        speed: true,
        transparent: false
      }
    }
  }
});



6. API


GLightbox对象上有方法、setter和getter。访问GLightbox对象的最简单方法是将调用的返回值设置为变量。例如:


lightbox.nextSlide(); // Go to next slide
lightbox.close(); // Close the lightbox



7. 方法


方法使用示例:


lightbox.nextSlide(); // Go to next slide
lightbox.close(); // Close the lightbox


OptionParametersDescription
opennodeOpen the lightbox, you can optionally pass a node.
openAtnumberOpen at specific index.
close-Close the lightbox.
reload-Reload the lightbox, after inserting content with ajax.
destroy-Destroy and remove all attached events.
prevSlide-Go to the previous slide.
nextSlide-Go to the next slide.
goToSlidenumberIndex of the slide.
insertSlideobject, indexInsert a slide at the specified index.
removeSlideindexRemove slide at the specified index.
getActiveSlide-Get active slide. It will return the active node.
getActiveSlideIndex-Get active slide. It will return the active slide index.
slidePlayerPlaynumberPlay video in the specified slide.
slidePlayerPausenumberPause video in the specified slide.
getSlidePlayerInstancenode, indexGet the player instance of the specified slide.
getAllPlayers-Get all players instance.
setElements[]Update the lightbox gallery elements.
onstring, functionSet an event listener. See Events section
oncestring, functionSet an event listener that will be triggered only once. See Events section


// Example set custom gallery items
// This overwrites all the items in the gallery
lightbox.setElements([
  {
    'href': 'https://picsum.photos/1200/800',
    'type': 'image' // Type is only required if GLightbox fails to know what kind of content should display
  },
  {
    'href': 'https://www.youtube.com/watch?v=Ga6RYejo6Hk',
    'type': 'video', // Type is only required if GLightbox fails to know what kind of content should display
    'width': '900px',
  },
  {
    'content': '<p>some html to append in the slide</p>',
    'width': '900px',
  }
]);


// Insert a single slide at the end of all the items,
lightbox.insertSlide({
    href: 'video url...',
    width: '90vw'
});

// Insert a single slide at index 2 or pass 0 to add it at the start
lightbox.insertSlide({
    href: 'video url...',
    width: '90vw'
}, 2);

// You can insert a slide with a defined html
lightbox.insertSlide({
    content: '<p>some html to append in the slide</p>',
    width: '90vw'
}, 2);

// Or if you prefer you can pass a node
// and it will be inserted in the slide
lightbox.insertSlide({
    content: document.getElementById('inline-example'),
    width: '90vw'
}, 2);

// Remove the slide at index 2
lightbox.removeSlide(2);

// Open the lightbox
lightbox.open();

// You can also open the lightbox at a specific index
lightbox.openAt(2);

// So imagine that you are making an ajax request that returns some html
// You can create an empty instance and append the content once is returned

const ajaxExample = GLightbox({ selector: null }); // or you can set the selector empty selector: ''

doAjaxCall({...}).then(response => {
    ajaxExample.insertSlide({
        width: '500px',
        content: response.html
    });
    ajaxExample.open();
})

// Or you could use the set elements method to empty all the slides if any

doAjaxCall({...}).then(response => {
    ajaxExample.setElements([
      {
        content: response.html
      }
    ]);
    ajaxExample.open();
})



8. 动画


动画是用CSS创建的,每个效果都有一个输入和输出值,它们用于将正确的类附加到节点。例如,如果您正在使用:


const glightbox = GLightbox({
  openEffect: 'zoom',
  closeEffect: 'fade',
  cssEfects: {
    // This are some of the animations included, no need to overwrite
    fade: { in: 'fadeIn', out: 'fadeOut' },
    zoom: { in: 'zoomIn', out: 'zoomOut' }
  }
});


打开效果将使用cssEffects.zoom.in,并将添加类gzoomIn,如果你查看CSS,你会看到:


.gzoomIn {
    animation: gzoomIn .5s ease;
}

@keyframes gzoomIn {
    from {
        opacity: 0;
        transform: scale3d(.3, .3, .3);
    }
    to {
        opacity: 1;
    }
}


添加自定义动画


你可以创建任何你想要的动画,你可以在Animate.css库中找到一些灵感,例如,你可以像这样添加反弹动画:


const glightbox = GLightbox({
  openEffect: 'bounce', // Define that we want the bounce animation on open
  cssEfects: {
    // register our new animation
    bounce: { in: 'bounceIn', out: 'bounceOut' }
  }
});

[CSS]
<style>
/*A g will be appended to the animation name so bounceIn will become gbounceIn */
.gbounceIn {
  animation: bounceIn 1.3s ease;
}

@keyframes bounceIn {
  from,
  20%,
  40%,
  60%,
  80%,
  to {
    animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }

  0% {
    opacity: 0;
    transform: scale3d(0.3, 0.3, 0.3);
  }

  20% {
    transform: scale3d(1.1, 1.1, 1.1);
  }

  40% {
    transform: scale3d(0.9, 0.9, 0.9);
  }

  60% {
    opacity: 1;
    transform: scale3d(1.03, 1.03, 1.03);
  }

  80% {
    transform: scale3d(0.97, 0.97, 0.97);
  }

  to {
    opacity: 1;
    transform: scale3d(1, 1, 1);
  }
}
</style>



9. 可主题化


您可以完全自定义GLightbox的结构,并使用CSS更改您想要的任何部分。


const customLightboxHTML = `<div id="glightbox-body" class="glightbox-container">
    <div class="gloader visible"></div>
    <div class="goverlay"></div>
    <div class="gcontainer">
    <div id="glightbox-slider" class="gslider"></div>
    <button class="gnext gbtn" tabindex="0" aria-label="Next" data-customattribute="example">{nextSVG}</button>
    <button class="gprev gbtn" tabindex="1" aria-label="Previous">{prevSVG}</button>
    <button class="gclose gbtn" tabindex="2" aria-label="Close">{closeSVG}</button>
</div>
</div>`;

let customSlideHTML = `<div class="gslide">
    <div class="gslide-inner-content">
        <div class="ginner-container">
            <div class="gslide-media">
            </div>
            <div class="gslide-description">
                <div class="gdesc-inner">
                    <h4 class="gslide-title"></h4>
                    <div class="gslide-desc"></div>
                </div>
            </div>
        </div>
    </div>
</div>`;

const glightbox = GLightbox({
  lightboxHTML: customLightboxHTML,
  slideHTML: customSlideHTML,
  skin: 'supercool'
});


你也可以定义一个皮肤名称,灯箱会附加类名“glightbox supercol”,这样你就可以用CSS自定义它,这将留下一个裸露的结构,这样你可以更改按钮的外观,等等。



相关链接


GitHub 地址 :  https://github.com/biati-digital/glightbox

官方网站 :https://lokeshdhakar.com/projects/lightbox/

易助科技网效果演示地址:  http://demo.easyzone.net.cn/plugin/glightbox/index.html