我想编写一个交互式翻页书来展示我的杂志设计,但这个翻页书只有在我进入“检查元素”模式或在移动设备上打开我的网站时才能正常工作。我是一名编程新手,使用了 turn.js 来实现翻页效果。
这是我的网页的 JS 代码
// Load navbar and footer into every page
document.addEventListener("DOMContentLoaded", () => {
// Load the navbar
fetch("navbar.html")
.then((res) => res.text())
.then((data) => {
document.getElementById("navbar").innerHTML = data;
});
// Load the footer
fetch("footer.html")
.then((res) => res.text())
.then((data) => {
document.getElementById("footer").innerHTML = data;
});
// Wait for the DOM to fully load before initializing Turn.js
const flipbook = document.querySelector(".flipbook");
// Ensure the flipbook exists before initializing Turn.js
if (flipbook) {
const initializeFlipbook = () => {
const screenWidth = window.innerWidth;
// Adjust flipbook size based on screen width
let flipbookWidth = 800;
let flipbookHeight = 500; // Default aspect ratio: 16:10
if (screenWidth <= 768) {
flipbookWidth = 600;
flipbookHeight = flipbookWidth * 0.625; // Maintain aspect ratio
}
if (screenWidth <= 480) {
flipbookWidth = 320;
flipbookHeight = flipbookWidth * 0.625; // Maintain aspect ratio
}
// Set the container's dimensions
const flipbookContainer = document.querySelector(".flipbook-container");
flipbookContainer.style.width = `${flipbookWidth}px`;
flipbookContainer.style.height = `${flipbookHeight}px`;
// Force reflow
flipbook.offsetHeight;
// Initialize Turn.js
$(flipbook).turn({
width: flipbookWidth,
height: flipbookHeight,
autoCenter: true,
elevation: 50,
gradients: true,
when: {
turning: function (event, page, view) {
console.log("Turning to page:", page);
},
},
});
};
// Initialize the flipbook
initializeFlipbook();
// Reinitialize the flipbook on window resize
window.addEventListener("resize", () => {
if ($(flipbook).data("turn")) {
$(flipbook).turn("destroy"); // Destroy the existing flipbook
}
initializeFlipbook(); // Reinitialize with new dimensions
});
}
$(flipbook).turn({
width: flipbookWidth,
height: flipbookHeight,
autoCenter: true,
elevation: 50,
gradients: true,
when: {
turning: function (event, page, view) {
console.log("Turning to page:", page);
},
},
});
console.log("Turn.js initialized!");
});
如果有帮助的话,这是我的 github 存储库:https://github.com/iiRosie1/portfolio
您可以查看网页,了解它目前是如何损坏的:https://iirosie1.github.io/portfolio/brandmagazine.html
任何帮助都值得感激!