jQuery是一个快速、简洁的JavaScript库,而CSS是用于样式设计的语言。结合两者可以有效地提高网页的响应性(Responsiveness),即让网页能够适应不同设备屏幕尺寸和用户交互。
$(window).resize(function() {
if ($(window).width() < 768) {
$('.menu').css({
'display': 'none',
'position': 'absolute',
'top': '60px',
'left': '0',
'width': '100%'
});
} else {
$('.menu').css({
'display': 'block',
'position': 'relative',
'top': 'auto',
'left': 'auto',
'width': 'auto'
});
}
});
function loadCSSBasedOnDevice() {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
$('head').append('<link rel="stylesheet" href="mobile.css" type="text/css" />');
} else {
$('head').append('<link rel="stylesheet" href="desktop.css" type="text/css" />');
}
}
$(document).ready(loadCSSBasedOnDevice);
$('.interactive-element').hover(
function() {
$(this).css({
'background-color': '#f0f0f0',
'transition': 'background-color 0.3s ease'
});
},
function() {
$(this).css('background-color', '#ffffff');
}
);
function makeTableResponsive() {
$('table').each(function() {
if ($(window).width() < 600) {
$(this).addClass('responsive-table');
$(this).find('thead').hide();
$(this).find('tr').each(function() {
$(this).find('td').each(function(i) {
$(this).attr('data-label', $(this).closest('table').find('th').eq(i).text());
});
});
} else {
$(this).removeClass('responsive-table');
$(this).find('thead').show();
$(this).find('td').removeAttr('data-label');
}
});
}
$(window).on('resize load', makeTableResponsive);
/* 响应式表格样式 */
.responsive-table {
width: 100%;
border-collapse: collapse;
}
.responsive-table tr {
display: block;
margin-bottom: 10px;
border: 1px solid #ddd;
}
.responsive-table td {
display: block;
text-align: right;
padding: 8px;
border-bottom: 1px solid #eee;
}
.responsive-table td:before {
content: attr(data-label);
float: left;
font-weight: bold;
}
/* 响应式菜单样式 */
@media (max-width: 767px) {
.menu {
display: none;
}
.menu.active {
display: block;
}
}
// 使用防抖技术优化resize事件
var resizeTimer;
$(window).on('resize', function(e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
// 响应式代码在这里执行
makeTableResponsive();
}, 250);
});
通过合理结合jQuery和CSS,可以创建出高度响应式的网页,提供良好的用户体验。
没有搜到相关的文章