首先:我已经问了这个问题: How to scroll to next div using Javascript?
但这只是使用带有静态页面的javascript。
现在,我有一个动态页面,可从数据库中加载数据。
PHP:
<html>
<head>
<title>Page</title>
<link rel="stylesheet" href="main.php">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css">
<script src="jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<?php
//DB connection
$db_hostname = "localhost";
$db_username = "root";
$db_password = "";
$db_db = "php_testing";
$conn = new mysqli($db_hostname,$db_username,$db_password,$db_db);
$sql = "SELECT * FROM podaci";
$result = $conn->query($sql);
//print_r($result);die;
if ($result->num_rows > 0) {
// Show each data returned by mysql
while($row = $result->fetch_assoc()) {
?>
<div class="conteiner active">
<div class="g name">
<i class="fas fa-user"></i>
<h class="ime"><?= $row['ime'] ?>
<?= $row['prezime'] ?>
</h>
</div>
<div class="g date">
<i class="fas fa-calendar-alt"></i>
<h class="ime"><?= $row['datum_rodjenja'] ?></h>
</div>
<div class="g school">
<i class="fas fa-school"></i>
<h class="ime"><?= $row['skola'] ?></h>
</div>
<div class="g movie">
<i class="fas fa-film"></i>
<h class="ime"><?= $row['omiljeni_film'] ?></h>
</div>
<div class="g address">
<i class="fas fa-map-marker-alt"></i>
<h class="ime"><?= $row['adresa'] ?></h>
</div>
<div class="g uspjeh">
<i class="fas fa-marker"></i>
<h class="ime"><?= $row['uspijeh'] ?></h>
</div>
<div class="g jelo">
<i class="fas fa-utensils"></i>
<h class="ime"><?= $row['omiljeno_jelo'] ?></h>
</div>
<div class="g pjesma">
<i class="fas fa-music"></i>
<h class="ime"><?= $row['omiljena_pjesma'] ?></h>
</div>
<button class="next">NEXT</button>
</div>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
这是我的网站现在的样子。 .conteiner
设置为采用height: 100vh
我已经添加了main.js
文件,因此,当我单击NEXT
按钮时,它将滚动到下一个.conteiner
JAVASCRIPT:
$(".next").click(function() {
var $target = $('.conteiner.active').next('.conteiner');
if ($target.length == 0)
$target = $('.conteiner:first');
$('html, body').animate({
scrollTop: $target.offset().top
}, 'slow');
});
答案 0 :(得分:0)
在您的PHP更改中
while($row = $result->fetch_assoc()) {
?>
<div class="conteiner active">
到
$first = true;
while($row = $result->fetch_assoc()) {
?>
<div class="conteiner <?php if ($first) {$first = false; echo 'active';} ?>">
在您的JS中:
$(".next").click(function() {
var $active = $('.conteiner.active');
var $target = $active.next('.conteiner');
if ($target.length == 0)
$target = $('.conteiner').first();
$active.removeClass('active');
$target.addClass('active');
$('html, body').animate({
scrollTop: $target.offset().top
}, 'slow');
});