javascript 如何创建多个动态图像滑块?[仅使用 PHP、MySQL 和 vanilla JS !]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51827471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:42:39  来源:igfitidea点击:

How to create multiple dynamic image slider ? [using PHP, MySQL & vanilla JS only ! ]

javascriptphpmysqlimageposting

提问by Coding Noob


I'm new to PHP and JS programming and need help with my website project.
In a other question, I had a problem with an image posting system, which is solved:
SOS! How to display image albums in posts? [using PHP and MYSQL only].

Now I want to modify this posting system with dynamic image sliders. (next Level ^^)
At the end, it must be possible to scroll down trough the postsand in each post with more then 1 image, it must be possible to slide left & right through the images of this album.

Image Slider
I inspired me by a full screen image slider: https://codepen.io/bradtraversy/pen/boydaE
and a carousel slider: https://www.youtube.com/watch?v=KcdBOoK3Pfw
which are both vanilla but static (without database).


Below you can see my php file, where everything comes together.


我是 PHP 和 JS 编程的新手,需要有关我的网站项目的帮助。
在另一个问题中,我遇到了图像发布系统的问题,已解决:
SOS!如何在帖子中显示相册?[仅使用 PHP 和 MYSQL]

现在我想用动态图像滑块修改这个发布系统。(下一级^^)
最后,必须可以向下滚动帖子,并且在每个帖子中包含超过 1 张图片,必须可以左右滑动浏览此相册的图片

图像滑块
我的灵感来自全屏图像滑块:https: //codepen.io/bradtraversy/pen/boydaE
和轮播滑块:https: //www.youtube.com/watch?v=KcdBOoK3Pfw
它们都是普通但静态的(没有数据库)。


您可以在下面看到我的 php 文件,其中包含所有内容。

display.php

显示.php



<!DOCTYPE html>
<html>
<body>
<?php
$db = mysqli_connect("localhost", "root", "", "post_images");    

$result = mysqli_query($db, "SELECT * FROM posts");
while ($row = mysqli_fetch_array($result)) {
   echo "<div class=\"post_container\">";
     echo $row['post_title'];
     echo "<div class=\"image_container\">";
     SELECT img_file, img_title FROM images WHERE post_id = " .$rowx['id_post']);

     if(mysqli_num_rows($resultx) > 0) {
        if(mysqli_num_rows($resultx) == 1) {
           echo "<div class=\"post_image_displayer\">";
             while ($rowx = mysqli_fetch_array($resultx)) {
               echo "<img src='../folder_image_uploads/".$rowx['img_file']."' >";
               echo $rowx['img_title'];
             }
           echo "</div>";
        }
        elseif(mysqli_num_rows($resultx) > 1) {
           echo "<div class=\"post_image_slider\">";
             include_once 'incl_image_slider.php';
           echo "</div>";
        }
     }
     echo "</div>";
   echo "</div>";
}
?>
</body>
</html>



This code works perfectly, if there would be only 1slider on this page. You see, I used include_once 'incl_image_slider.php';. If I would use only include 'incl_image_slider.php';, the page go crazy ... (only by the image slider). Even if everything has a classand no unique id.

如果此页面上只有1 个滑块,则此代码完美运行。你看,我使用了include_once 'incl_image_slider.php'; . 如果我只使用include 'incl_image_slider.php'; ,页面变得疯狂......(仅通过图像滑块)。即使所有东西都有一个并且没有唯一的id

incl_image_slider.php

incl_image_slider.php



<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="includes/incl_carousel_slider_style.css">
</head>

<div class="carousel-container">
    <div class="carousel-slide">
        <?php
        $db = mysqli_connect("localhost", "root", "", "post_images");
        $result = mysqli_query($db, "SELECT * FROM posts");
        $row = mysqli_fetch_array($result);
        $resultx = mysqli_query($db, "SELECT img_file, img_title FROM images WHERE post_id =".$row['id_post']);

        $rowz = mysqli_fetch_all($resultx, MYSQLI_ASSOC);
            echo "<img src='folder_img_uploads/".$rowz[0]['img_file']."' >";
            echo "<img src='folder_img_uploads/".$rowz[1]['img_file']."' >";
            echo "<img src='folder_img_uploads/".$rowz[2]['img_file']."' >";
            echo "<img src='folder_img_uploads/".$rowz[3]['img_file']."' >";
            echo "<img src='folder_img_uploads/".$rowz[4]['img_file']."' >";
        ?>
    </div>
</div>
<button class="prevBtn">Prev</button>
<button class="nextBtn">Next</button>

<script src="incl_image_slider_app.js"></script>


The problem with this is, I have to know for each post, how many images inside. So this can't be used dynamically with a database, someone have an idea what to change?


问题是,我必须知道每个帖子里面有多少张图片。所以这不能与数据库一起动态使用,有人知道要改变什么吗?

incl_image_slider_app.js

incl_image_slider_app.js

Partly this is from: https://codepen.io/bradtraversy/pen/boydaE

部分来自:https: //codepen.io/bradtraversy/pen/boydaE

let sliderImages = document.querySelectorAll(".carousel-slide"),
arrowLeft = document.querySelector(".prevBtn"),
arrowRight = document.querySelector(".nextBtn"),
current = 0;

// Clear all images
function reset()
{
  for (let i = 0; i < sliderImages.length; i++)
  {
    sliderImages[i].style.display = "none";
  }
 }
 // Init slider
 function startSlide()
 {
   reset();
   sliderImages[0].style.display = "block";
 }
 // Show prev
 function slideLeft()
 {
   reset();
   sliderImages[current - 1].style.display = "block";
   current--;
}
// Show next
function slideRight()
{
  reset();
  sliderImages[current + 1].style.display = "block";
  current++;
}
// Left arrow click
arrowLeft.addEventListener("click", function()
{
  if (current === 0)
  {
    current = sliderImages.length;
  }
slideLeft();
});

// Right arrow click
arrowRight.addEventListener("click", function()
{
  if (current === sliderImages.length - 1)
  {
    current = -1;
  }
slideRight();
});

startSlide();


Actually this image slider don't slide, no idea why? But it shows the first image of a post. And it is not possible to bring this multiple times for each post, in my display.php

I hope there is someone who can help me.
Best Regards :)


实际上这个图像滑块不滑动,不知道为什么?但它显示了帖子的第一张图片。而且不可能为每个帖子多次带来这个,在我的 display.php

我希望有人可以帮助我。
最好的祝福 :)

回答by Stanzi1791

I think you want something like this. I've used Flickity Slider (pure JavaScript) instead of your JavaScript because I couldn't get that working (but then again, I can barely code a foreach loop in JavaScript :( ), hopefully this will give you something to start with. :)

我想你想要这样的东西。我使用了 Flickity Slider(纯 JavaScript)而不是你的 JavaScript,因为我无法让它工作(但话说回来,我几乎无法在 JavaScript 中编写 foreach 循环 :( ),希望这会给你一些开始。 :)

https://flickity.metafizzy.co/

https://flickity.metafizzy.co/

<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">
<!-- JavaScript -->
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>
</head>
<body>

<?php
$db = mysqli_connect("localhost", "root", "", "post_images");      
$result = mysqli_query($db, "SELECT * FROM posts");
?>

<?php while ($row = mysqli_fetch_array($result)) : ?>

    <div class="post_container">$row['post_title'];

        <?php $resultx = mysqli_query($db, "SELECT img_file, img_title FROM images WHERE post_id = " .$row['id_post']); ?>

        <?php if (mysqli_num_rows($resultx) == 1) : ?>

        <div class="image_container">

            <div class="post_image_displayer">

                <?php while ($rowx = mysqli_fetch_array($resultx)) : ?>
                <img src='../folder_image_uploads/<?php echo $rowx['img_file']; ?>'><?php echo $rowx['img_title']; ?>
                <?php endwhile; ?>

            </div>

        </div>

        <?php elseif(mysqli_num_rows($resultx) > 1) : ?>

            <div class="main-carousel" data-flickity='{ "cellAlign": "left", "contain": true }'>

                <?php while ($rowx = mysqli_fetch_array($resultx)) : ?>
                <div class="carousel-cell"><img src='../folder_image_uploads/<?php echo $rowx['img_file']; ?>' ></div>
                <?php endwhile; ?>

            </div>

        <?php endif; ?>

    </div>

<?php endwhile; ?>

</body>
</html>

The CSS and JavaScript files in the header include the slider plugin.

标题中的 CSS 和 JavaScript 文件包括滑块插件。

Then, the first SQL query gets all of the posts, the while loops over each one.

然后,第一个 SQL 查询获取所有帖子,while 循环遍历每个帖子。

For each post, the second SQL query gets the images for the current post.

对于每个帖子,第二个 SQL 查询获取当前帖子的图像。

If there's only one image, it is printed inside a <div class="image_container">.

如果只有一张图片,它会打印在一个<div class="image_container">.

If there's more than one image, they're printed inside a <div class="main-carousel">which tells the JavaScript plugin together with the data-flickity='{ "cellAlign": "left", "contain": true }'that it needs to show these in a slider.

如果有多个图像,它们会打印在 a 中<div class="main-carousel">,它告诉 JavaScript 插件以及data-flickity='{ "cellAlign": "left", "contain": true }'它需要在滑块中显示这些图像。

The individual images in the slider are each printed inside a <div class="carousel-cell">which is also required by the plugin.

滑块中的各个图像都打印在<div class="carousel-cell">插件中,这也是插件所需的。

This is repeated for all images of all posts, you don't need to use an include file.

这对所有帖子的所有图像重复,您不需要使用包含文件。

Update with the slider by sinisake from this post

这篇文章中通过 sinisake 更新滑块

<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<link rel="stylesheet" href="">
<!-- JavaScript -->
<script src=""></script>
</head>
<body>

<?php
$db = mysqli_connect("localhost", "root", "", "post_images");      
$result = mysqli_query($db, "SELECT * FROM posts");
?>

<?php while ($row = mysqli_fetch_array($result)) : ?>

    <div class="post_container">$row['post_title'];

        <?php $resultx = mysqli_query($db, "SELECT img_file, img_title FROM images WHERE post_id = " .$row['id_post']); ?>

        <?php if (mysqli_num_rows($resultx) == 1) : ?>

        <div class="image_container">

            <div class="post_image_displayer">

                <?php while ($rowx = mysqli_fetch_array($resultx)) : ?>
                <img src='../folder_image_uploads/<?php echo $rowx['img_file']; ?>'><?php echo $rowx['img_title']; ?>
                <?php endwhile; ?>

            </div>

        </div>

        <?php elseif(mysqli_num_rows($resultx) > 1) : ?>

            <div class="slideshow-container">

                <?php $rowsx = mysqli_fetch_all($resultx, MYSQLI_ASSOC); ?>

                <?php foreach ($rowsx as $key => $rowx) : ?>

                  <div class="mySlides fade">
                    <div class="numbertext"><?php echo $key + 1; ?> / <?php echo count($rowsx); ?></div>
                    <img src='../folder_image_uploads/<?php echo $rowx['img_file']; ?>' style="width:100%">
                    <div class="text">Caption Text</div>
                  </div>

                <?php endforeach; ?>

                  <a class="prev" >&#10094;</a>
                  <a class="next">&#10095;</a>
                <div style="text-align:center">

                <?php foreach ($rowsx as $rowx) : ?>
                  <span class="dot"></span>
                <?php endforeach; ?>

                </div>  

            </div>

        <?php endif; ?>

    </div>

<?php endwhile; ?>

</body>
</html>

What I've changed here, I've stored the entire result of the second SQL query in an array ($rowsx), because then I can loop over it twice (with foreachinstead of while).

我在这里所做的更改是,我将第二个 SQL 查询的整个结果存储在一个数组 ( $rowsx) 中,因为这样我就可以循环遍历它两次(用foreach代替while)。

The first time I loop over it is to print the individual images, and when all images have been printed I loop over the array a second time to print the "dots" for the navigation, because there need to be the same number of dots as there are images in the slider.

我第一次循环它是打印单个图像,当所有图像都打印完后,我第二次循环数组以打印导航的“点”,因为需要与相同数量的点滑块中有图像。