Repeating a character across the full width of an element

我怕爱的太早我们不能终老 提交于 2019-12-13 04:15:33

问题


I am trying to write a function using JavaScript and jQuery (since I'm already using jQuery for my site) to detect the width of the view port and output a character repeated across the full width.

I am trying to make a website that looks like a unix terminal and I would like the table headers to use the equal sign to repeat across the width of the screen (tables are set to width: 100%;). I know I probably could just make a simple image of the equal sign and set it to repeat-x using CSS on an empty header row but I prefer it to be text. I have been playing around with arrays and this is what I have so far.

var windowWidth =$(window).width();
document.write( array( windowWidth ) ).join( '=' ) );

I know this is broken, but that is where I left off because I haven't been able to figure out what search terms I should be using to find an answer. So if anyone wouldn't mind either helping me write this or point me in the right direction I would appreciate it.


回答1:


This can probably be improved, but you could do it by:

  • Appending a single character to the body, and get its width, then remove it.
  • Divide the width of the body by the width of the character to get the number of times to repeat the character.

Example

var $char = $('<span>').css({ padding: 0, margin: 0 }).text('=').appendTo('body'),
    charWidth = $char.width(),
    numberOfChars = parseInt(( $('body').width() / charWidth ).toFixed(), 10);

$char.remove();
document.write( Array(numberOfChars).join('=') );

Here's a fiddle




回答2:


my take on it:

for (
    var x = Math.floor(
    $("body").append("<span>=</span>").width() / $($("body").children()[0]).width());

    x > 1;

    x-- && $("body").append("<span>=</span>")
);

change $("body") to whatever element you wanna add your stuff into.

http://jsfiddle.net/8suma/



来源:https://stackoverflow.com/questions/24136784/repeating-a-character-across-the-full-width-of-an-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!