gpt4 book ai didi

angular - Swiper 在 Angular 5 中不工作

转载 作者:行者123 更新时间:2023-12-02 00:18:14 29 4
gpt4 key购买 nike

我正在尝试将 nolimts4web swiper 集成到我的 Angular 5 项目中,我在 index.html 文件中使用了

<head>
...
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.2.2/css/swiper.min.css">
</head>
<body>
...
<script
src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.2.2/js/swiper.min.js">
</script>
</body>

将其放入我的 HTML 文件中:

<div class="swiper-container">
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>

<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>

<div class="swiper-scrollbar"></div>
</div>

并通过将其放在 index.html 中的 body 标记末尾之前进行初始化:

<script>
var mySwiper = new Swiper ('.swiper-container', {
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
scrollbar: {
el: '.swiper-scrollbar',
},
})
</script>

发生的情况是,它在滑动器中显示了幻灯片 1,但是单击“下一步”按钮没有执行任何操作,而且我无法滑动,基本上操作不起作用。

最佳答案

请使用此library避免 Swiper 在 html 加载之前初始化。

---- 更新 1 ----

在我看来,您的问题与 HTML 的生命周期有关,这意味着 Swiper 在浏览器加载/解释 html 之前初始化。为了避免这个问题,您可以使用链接库或仅创建如下所示的组件:

// Don't forget to declare Global variable related to Swiper.
declare var Swiper: any;

@Component({
selector: 'swiper',
template: `
<div class="swiper-container">
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>

<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>

<div class="swiper-scrollbar"></div>
</div>
`
})
export class SwiperComponent implements AfterViewInit {
constructor(
private elementRef: ElementRef
) {}

//[...]

ngAfterViewInit() {
/**
* - Here you are 100% sure, html is present on DOM, Swiper is initialize and is able to find your DOM element.
* - Swiper constructor accept DOMElement as parameter, i recommand this approch to optimize DOM parsing.
* - Because you store Swiper instance as attribute, you will be able to control Swiper by javascript.
**/
this.swiper = new Swiper(this.elementRef.nativeElement.querySelector('.swiper-container'), {
//Here you can provide Swiper config
});
}
}

Online sample

关于angular - Swiper 在 Angular 5 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49810045/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com