WordPress中Owl Carousel导航图片如何动态引入站点URL?
解决WordPress中Owl Carousel导航图片动态站点URL的问题
你可以直接通过字符串拼接或者ES6模板字符串的方式,将已有的siteURLData.root_url变量插入到navText的图片src属性中,具体修改如下:
方案1:使用ES6模板字符串(推荐,代码更简洁)
$(".home-slider-wrapper").owlCarousel({ autoplay: true, autoplayHoverPause: false, loop: true, nav: true, // Show next and prev buttons dots: false, slideSpeed: 2500, smartSpeed: 1000, responsive: { 0: { items: 1, } }, navText: [ `<img src="${siteURLData.root_url}/assets/images/angel-left.svg" alt="angle left" class="owl-prev__img" width="16px" height="14px">`, `<img src="${siteURLData.root_url}/assets/images/angel-right.svg" alt="angle right" class="owl-next__img" width="16px" height="14px">`, ], });
方案2:使用传统字符串拼接
如果项目环境不支持ES6语法,可以用这种方式:
$(".home-slider-wrapper").owlCarousel({ autoplay: true, autoplayHoverPause: false, loop: true, nav: true, // Show next and prev buttons dots: false, slideSpeed: 2500, smartSpeed: 1000, responsive: { 0: { items: 1, } }, navText: [ '<img src="' + siteURLData.root_url + '/assets/images/angel-left.svg" alt="angle left" class="owl-prev__img" width="16px" height="14px">', '<img src="' + siteURLData.root_url + '/assets/images/angel-right.svg" alt="angle right" class="owl-next__img" width="16px" height="14px">', ], });
注意事项
- 确保
siteURLData.root_url在这段Owl Carousel初始化代码执行前已经被正确输出到前端(比如你通过wp_localize_script在functions.php中定义的全局变量) - 如果
siteURLData.root_url结尾本身带有斜杠,记得去掉拼接时的/,避免出现//assets/...的路径错误
内容的提问来源于stack exchange,提问作者Alipvd
相关产品推荐
相关产品推荐

