I want to set a youtube video to 100% width so that it scales appropriately in a dynamic width column on a web page I am designing.
开发者_开发技巧The problem is that the height doesn't behave like the height of an image. Instead of scaling proportionately, it either collapses (if set to "auto" or left blank) or it scales seemingly random if set to a percentage.
How can I get it to remain proportionate while still dynamic?
With jQuery you could do this:
newwidth = 200; // or worked out dynamically from width of an object after window resize
mov = $('object') // i.e. grab the object, perhaps with another selector too
oldheight = mov.attr('height')
oldwidth = mov.attr('width')
newheight = newwidth/oldwidth * oldheight
mov.attr('width', newwidth).attr('height', newheight)
EDIT
I've now just created this for a hack I'm working on. In coffeescript because it's so much nicer:
resize_youtube_to_container = (obj) ->
newwidth = obj.closest('div').width() # find the width from parent div
oldheight = obj.attr('height')
oldwidth = obj.attr('width')
newheight = Math.round(newwidth/oldwidth * oldheight)
obj.attr('width', newwidth).attr('height', newheight)
return obj
$(document).ready = ->
movs = $('object, embed') # need to do both object and embed I think...
movs.each -> resize_youtube_to_container($(this))
$pattern = "/height=\"[0-9]*\"/";
$string = preg_replace($pattern, "height='120'", $rs['url']);
$pattern = "/width=\"[0-9]*\"/";
$string = preg_replace($pattern, "width='200'", $string);
echo $string;
精彩评论