更新时间:2023-09-06 19:17:52
window.resize
是正确的事件,但它不会在页面加载时触发.但是,您可以将 .trigger('resize')
添加到您的代码中,使其在页面加载时触发:
window.resize
is the correct event but it doesn't fire on page-load. You can however just add .trigger('resize')
to your code to make it fire on page-load:
$(window).bind('resize', function(){
var containerSize = $('.container').width(),
textPercentage = 0.17391304347826086956521739130435, /* 40/230 */
textRatio = containerSize * textPercentage,
textEms = textRatio / 14;
$('.container h3').css(fontSize, textEms+"em");
}).trigger('resize');
您将要在 document.ready
之后运行此代码,以确保您获得的容器宽度正确.您还可以将此代码放在 HTML 文档的底部(无论是否使用 document.ready
事件处理程序),这将确保在您运行此代码时元素可用:
You are going to want to run this code after document.ready
to make sure the width you are getting for the container is correct. You could also place this code at the bottom of your HTML document (which you should do with or without the document.ready
event handler) which will make sure the elements are available when you run this code:
//wait for `document.ready` to fire
$(function () {
//cache the .container and H3 elements
var $container = $('.container'),
$h3 = $container.find('h3');
//bind event handler to `window.resize`
$(window).bind('resize', function(){
//get the width of the container
var containerSize = $container.width(),
textPercentage = 0.17391304347826086956521739130435, /* 40/230 */
textRatio = containerSize * textPercentage,
textEms = textRatio / 14;
$h3.css('fontSize', textEms+"em");
}).trigger('resize');
});
请注意,我缓存了 H3
元素,因此不必在每个 resize
事件中都选择它,因为当您实际调整大小时浏览器会触发大量此类事件.
Notice that I cached the H3
element(s) so it/then don't have to be selected every resize
event, because when you actually re-size your browser there are tons of these events that fire.