Chào mọi người, bài viết này mình chia sẽ đến mọi người một tiện ích rút gọn link đơn giản không sữ dụng
Bước 1. Mọi người thêm đoạn code
Bước 2. mọi người thêm đoạn code
Bước 3. Các bạn đặt đoạn code
Database để lưu trữ, mà đơn giản chỉ cần dùng HTML, CSS, Javascript để tạo trang rút gọn liên kết khá thú vị cho mọi người sữ dụng, với giao diện đơn giản nhẹ nhàng, tốc độ tải trang nhanh, giúp cho mọi người làm trang rút gọn liên kết của bản thân mà không tốn quá nhiều chi phí để thuê hosting, hay sever để chạy. Mọi người có thể áp dụng trực tiếp lên giao diện Blogger hiện tại để áp dụng thủ thuật trên.Chúng ta bắt đầu nhé.
Bước 1. Mọi người thêm đoạn code CSS này vào để hiển thị bố cục và giao diện.
.layout {
display: flex;
}
.sidebar {
width: 30%;
}
.content {
width: 70%;
}
.shortener-box {
max-width: 500px;
margin: 20px auto;
display: flex;
flex-direction: column;
gap: 10px;
}
.shortener-box input,
.shortener-box button {
padding: 10px;
font-size: 15px;
}
.shortener-box button {
background: #2563eb;
color: #fff;
border: 0;
cursor: pointer;
}
.shortener-box button:hover {
opacity: 0.9;
}
Bước 2. mọi người thêm đoạn code Javascript để thực hiện việc rút gọn liên kết.
const db = JSON.parse(localStorage.getItem("shortDB") || "{}");
function shortenUrl(){
const longUrl = document.getElementById("longUrl").value;
if(!longUrl) return alert("Please enter the link!");
let code;
do {
code = Math.random().toString(36).slice(2,8);
} while(db[code]);
db[code] = longUrl;
localStorage.setItem("shortDB", JSON.stringify(db));
document.getElementById("shortUrl").value =
location.origin + location.pathname + "?link=" + code;
}
/* Auto redirect */
(function(){
const link = new URLSearchParams(location.search).get("link");
if(link && db[link]) location.href = db[link];
})();
Với đoạn Javascript này việc rút gọn liên kết sẽ còn 6 ký tự.
Bước 3. Các bạn đặt đoạn code HTML để hiện thi khung như hình.
<div class="shortener-box">
<input type="url" id="longUrl" placeholder="Paste the link you want to shorten..." />
<button onclick="shortenUrl()">Shorten</button>
<input type="text" id="shortUrl" placeholder="The shortened link will appear here." readonly />
<div class="layout">
<aside class="sidebar"></aside>
<main class="content">Copyright By <a href='https://www.hung.pro.vn'>Hung.Pro.VN</a></main>
</div>
</div>
Như vậy đã hoàn thành tiện ích tạo trang rút gọn link, bây giờ mọi người có thể cùng xem và tận hưởng thành quả của bản thân.
hay đó em, tks e :)
ReplyDeletePost a Comment