Increase font size with JavaScript around fixed floated images in CSS columns

后端 未结 3 673
温柔的废话
温柔的废话 2021-01-21 09:44

I was searching for an html page, where i can acquire Font size of a text in a div to be increased using javascript and at the same time an image placed in that div should not b

相关标签:
3条回答
  • 2021-01-21 10:13

    If you add a style attribute to the div that contains the image to position it absolute, that might solve your problem.

    HTML snippet:

    <div>
        <div id="multicolumn4" >
            <span style='font-size:10px;'>
                <h1>The header of the columns</h1>
                <div class="imagediv">
                    <img id="Image-Maps_5201006280459541" src="images/im1.png" usemap="#Image-Maps_5201006280459541" border="0" width="192" height="256" alt="" />
                </div>
                <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
                <p>Nam ut sapien sed pede pulvin</p>
            </span>
        </div>
    </div>

    CSS:

    .imagediv{float:left; margin-top: 30px; padding: 3px; }
    

    Is this what you are looking for ?


    The way to make text go around an image is by setting the style attribute "Float" on that image, or a surrounding element, like a div.

    If you see that the image is changing position because the size of the text above the image increases, then that is just because that's how HTML works.

    The position in the HTML is important to determine where to show your element on the rendered webpage.

    With the information you gave, it is not clear enough how it should be. The code I provided lets the text go around the image, however the text ABOVE the div, or at least the image tag, will cause it to be pushed down.

    There is, though, one possibility that would allow you to do such a thing, but it reaches beyond my skills, and that would be to remove the image with Javascript, and insert it back at a higher place in the HTML.

    I hope I gave you enough information for you to think about a solution.

    0 讨论(0)
  • 2021-01-21 10:22

    This type of layout question has been asked before quite a few times :-)

    From a quick read of the links on that thread, it looks like it is not easy to do.

    Edit: Right, this one has been bugging me. I figured it was possible with a small amount very large amount of complex JavaScript/jQuery and set about making a demo.

    There is still some work to be done, since the <p> that contains the image has been left in a bad way (i.e. full of <span> elements). I also make no promises on the performance of this solution. It seems to work for me OK. Oh and also the Font + link will only work once as the actual size of the font it increases the text to is fixed.

    That said, I would really try and find an alternate solution to your problem or even question why you need to fix an image position in this way. It is going against the normal browser re-flow and rules.

    Edit: Improved demo that addresses the issues in the comments.

    Edit 2: Wow, I did not know how complex the CSS3 column layout must be for browsers! Height is calculated in order to make the columns more or less equal and that means that when I detach the <img> the height is adjusted. This adjusted height will be different if the font-size increases and the <img> is not removed. It's just not possible to determine the height of the result before the <img> is removed and added.

    That said, I have made it work with one major condition - that the column has a hard-coded height. I tried to make it work with a browser calculated height (as normal flow rules would dictate) but I think it might be very difficult without a lot more work. The only way I think this might work is moving the <img> element forwards one <span> (i.e. word) at a time until the correct position().top is reached. But that would be incredibly inefficient and probably slow the rendering down so much it will be unusable.

    So, here is my final demo which is working in Chrome 11 for me. Sorry I could not reach a complete solution with variable height but as I, and others, have said it really is breaking all the browser layout rules!

    Edit 3: When I said "final" demo I clearly didn't mean it. I accept your challenge to actually make this work properly with multiple images and I really hope that this time, I have got it. Please have a look at this new demo (working in Chrome12 for me) which works with the HTML you posted. I must admit that the JavaScript you posted was very complex. So I have re-factored everything to work with multiple images based on my original JavaScript.

    Edit 4: Quite a lot of edits now… but I found the bug. For each font increment or decrement the images are moved in the flow and potentially a margin-top added to move the image back to it's original position. But I was not clearing this CSS before re-calculating the position on a subsequent font size change.

    The key code added was:

    // clear any existing marginTop added on the images
    images.each(function() {
        $(this).css('marginTop', 0);
    });
    

    I also tidied up the JavaScript a bit more whilst I was there and fixed another bug with removing the <span> elements :-)

    Updated jsFiddle demo

    And just in case jsFiddle ever disappears, here is the complete solution as one HTML file:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
        //<![CDATA[
            $(function(){
                var fontSize = 15;
    
                // cannot store img.position().top or .left here because it is
                // before the browser has re-flowed the columns, therefore the
                // positions will be incorrect
                var imageTops = new Array;
                var imageLefts = new Array;
    
                $('#fontUp').click(function() {
                    reflow(1);
                });
    
                $('#fontDown').click(function() {
                    reflow(-1);
                });
    
                function reflow(fontSizeStep) {
                    storeImagePositions();
                    var fontLimitReached = changeFont(fontSizeStep);
                    if (!fontLimitReached) {
                        moveImages();
                    }
                    return false;
                }
    
                function changeFont(step) {
                    fontSize += step;
    
                    var fontSizeLimitReached = true;
    
                    if (fontSize > 30) {
                        fontSize = 30;
                    } else if (fontSize < 15) {
                        fontSize = 15;
                    } else {
                        fontSizeLimitReached = false;
                    }
    
                    if (!fontSizeLimitReached) {
                        $('p').css({fontSize: fontSize + 'px'});
                    }
    
                    return fontSizeLimitReached;
                }
    
                // initialize store of img top and left positions
                function storeImagePositions() {
                    if (imageTops.length == 0) { // only do it once
                        $('img').each(function() {
                            var imgPosition = $(this).position();
    
                            imageTops.push(imgPosition.top);
                            imageLefts.push(imgPosition.left);
                        });
                    }
                }
    
                function moveImages() {
                    // bye bye images
                    var images = $('img').detach();
    
                    // clear any existing marginTop added on the images
                    images.each(function() {
                        $(this).css('marginTop', 0);
                    });
    
    
                    // spanify paragraphs
                    $('#column > p').each(function() {
                        $(this).html('<span>' + $(this).html().replace(/\s\s+/g).replace(/(\s)/g,'</span>$1<span>') + '</span>');
                    });
    
                    var imageIndex = 0;
    
                    // iterate words, working out where we can move the img to in the flow and if
                    // we find a match, increment the index so that as we continue the each()
                    // the next image is evaluated for replacement
                    $('#column > p span').each(function() {
                        var wordPosition = $(this).position();
                        var wordLeft = wordPosition.left;
    
                        if (wordLeft >= imageLefts[imageIndex]) {
                            var wordBottom = wordPosition.top + $(this).height();
    
                            if (wordBottom > imageTops[imageIndex]) {
                                $(this).before(images[imageIndex]); // move img before this word
                                var newImgTop = $(images[imageIndex]).position().top;
                                $(images[imageIndex]).css({marginTop: imageTops[imageIndex] - newImgTop + 'px'});
                                imageIndex++; // increment index so remainder spans are being evaluated against the next image
                            }
                        }
                    });
    
                    // reverse the "spanification"
                    $('#column > p').each(function() {
                        $(this).html($(this).html().replace(/<\\?span>/g, '').trim());
                    });
                }
            });
        //]]>
        </script>
        <style type="text/css">
        div#column {
            -moz-column-count:6;
            -webkit-column-count:3;
            column-count:3;
            -webkit-column-width:100px;
            -moz-column-width:100px;
            column-width:100px;
            height:500px;
        }
    
        p {
            margin:0;
            clear:left;
            font-size:15px;
            text-align:justify;
        }
    
        img {
            float:left;
        }
        </style>
    </head>
    <body>
        <div><a href="#" id="fontUp" style="margin-right:10px">Font +</a><a href="#" id="fontDown">Font -</a></div>
        <div id="column">
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. <img src="http://www.avatarblast.com/avatars/cool/yoda.jpg" title="yoda" alt="yoda"/>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
            <p>The change of name from <img src="http://www.avatarblast.com/avatars/cool/yoda.jpg" title="yoda" alt="yoda"/> LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language. It has also been claimed that the language's name is the result of a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
            <p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>
            <p>Java EE includes several API specifications, such as JDBC, RMI, e-mail, JMS, web services, XML, etc., and defines how to coordinate them. Java EE also features some specifications unique to Java EE for components. These include Enterprise JavaBeans, Connectors, servlets, portlets (following the Java Portlet specification), JavaServer Pages and several web service technologies.<img src="http://www.avatarblast.com/avatars/cool/yoda.jpg" title="yoda" alt="yoda"/> This allows developers to create enterprise applications that are portable and scalable, and that integrate with legacy technologies. A Java EE application server can handle transactions, security, scalability, concurrency and management of the components that are deployed to it, in order to enable developers to concentrate more on the business logic of the components rather than on infrastructure and integration tasks.</p>
            <p>Java (Indonesian: Jawa) is an island of Indonesia. With a population of 136 million, it is the world's most populous island, and one of the most densely populated regions in the world. It is home to 60% of Indonesia's population. The Indonesian capital city, Jakarta, is in west Java.  Much of Indonesian history took place on Java; it was the centre of powerful Hindu-Buddhist empires, Islamic sultanates, the core of the colonial Dutch East Indies, and was at the centre of Indonesia's campaign for independence. The island dominates Indonesian social, political and economic life.</p>
        </div>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-21 10:27

    Updated Html for images which spans over multiple columns

     <html>
      <head>
        <title>Test</title>
        <g:javascript src="jquery.js"/>
        <script type="text/javascript">
               $(function(){
                var fontSize = 16;
    
                // cannot store img.position().top or .left here because it is
                // before the browser has re-flowed the columns, therefore the
                // positions will be incorrect
                var imageTops = new Array;
                var imageLefts = new Array;
    
                $('#fontUp').click(function() {
                    reflow(1);
                });
    
                $('#fontDown').click(function() {
                    reflow(-1);
                });
    
                function reflow(fontSizeStep) {
                    storeImagePositions();
                    var fontLimitReached = changeFont(fontSizeStep);
                    if (!fontLimitReached) {
             //           moveImages();
                    }
                    return false;
                }
    
                function changeFont(step) {
                    fontSize += step;
    
                    var fontSizeLimitReached = true;
    
                    if (fontSize > 30) {
                        fontSize = 30;
                    } else if (fontSize < 16) {
                        fontSize = 16;
                    } else {
                        fontSizeLimitReached = false;
                    }
    
                    if (!fontSizeLimitReached) {
                //      alert(fontSize)
                        $('p').css({fontSize: fontSize + 'px'});
                    }
    
                    return fontSizeLimitReached;
                }
    
                // initialize store of img top and left positions
                function storeImagePositions() {
                    if (imageTops.length == 0) { // only do it once
                        $('img').each(function() {
                            var imgPosition = $(this).position();
    
                            imageTops.push(imgPosition.top);
                            imageLefts.push(imgPosition.left);
                        });
                    }
                }
    
                function moveImages() {
                    // bye bye images
                    var images = $('img').detach();
    
                    // clear any existing marginTop added on the images
                    images.each(function() {
                        $(this).css('marginTop', 0);
                    });
    
    
                    // spanify paragraphs
                    $('#column > p').each(function() {
                        $(this).html('<span>' + $(this).html().replace(/\s\s+/g).replace(/(\s)/g,'</span>$1<span>') + '</span>');
                    });
    
                    var imageIndex = 0;
    
                    // iterate words, working out where we can move the img to in the flow and if
                    // we find a match, increment the index so that as we continue the each()
                    // the next image is evaluated for replacement
                    $('#column > p span').each(function() {
                        var wordPosition = $(this).position();
                        var wordLeft = wordPosition.left;
    
                        if (wordLeft >= imageLefts[imageIndex]) {
                            var wordBottom = wordPosition.top + $(this).height();
    
                            if (wordBottom > imageTops[imageIndex]) {
                                $(this).before(images[imageIndex]); // move img before this word
                                var newImgTop = $(images[imageIndex]).position().top;
                                $(images[imageIndex]).css({marginTop: imageTops[imageIndex] - newImgTop + 'px'});
                                imageIndex++; // increment index so remainder spans are being evaluated against the next image
                            }
                        }
                    });
    
                    // reverse the "spanification"
                    $('#column > p').each(function() {
                        $(this).html($(this).html().replace(/<\\?span>/g, '').trim());
                    });
                }
            });
        //]]>
        </script>
        <style type="text/css">
          div#column {
            margin-left:20px;
            -moz-column-width: 250px;
            -moz-column-gap: 20px;
            -webkit-column-width: 250px;
            -webkit-column-gap: 20px;
            height: 850px;
          }
    
          p {
            margin:0;
            clear:left;
            font-size:16px;
            text-align:justify;
          }
    
          img {
            float:left;
            margin-top: 2px;
            margin-right: 10px;
            position:fixed;
          }
        </style>
      </head>
      <body>
        <div><a href="#" id="fontUp" style="margin-right:10px">Font +</a><a href="#" id="fontDown">Font -</a></div>
        <div><img src="${createLinkTo(dir:'images',file:'Winter.jpg')}" height="250" width="660" id="image" title="yoda" alt="yoda"/></div>
              <div id="column" style="margin-top: 255px;">
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
                <p>The change of name from  LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion,  giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language. It has also been claimed that the language's name is the result of a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
                <p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>
                <p>Java EE includes several API specifications, such as JDBC, RMI, e-mail, JMS, web services, XML, etc., and defines how to coordinate them. Java EE also features some specifications unique to Java EE for components. These include Enterprise JavaBeans, Connectors, servlets, portlets (following the Java Portlet specification), JavaServer Pages and several web service technologies. This allows developers to create enterprise applications that are portable and scalable, and that integrate with legacy technologies.  A Java EE application server can handle transactions, security, scalability, concurrency and management of the components that are deployed to it, in order to enable developers to concentrate more on the business logic of the components rather than on infrastructure and integration tasks.</p>
                <p>Java (Indonesian: Jawa) is an island of Indonesia. With a population of 136 million, it is the world's most populous island, and one of the most densely populated regions in the world. It is home to 60% of Indonesia's population. The Indonesian capital city, Jakarta, is in west Java.  Much of Indonesian history took place on Java; it was the centre of powerful Hindu-Buddhist empires, Islamic sultanates, the core of the colonial Dutch East Indies, and was at the centre of Indonesia's campaign for independence. The island dominates Indonesian social, political and economic life.</p>
                <p>Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl, and Smalltalk. It can be used as a scripting language for the Java Platform.
                  Groovy uses a Java-like bracket syntax. It is dynamically compiled to Java Virtual Machine (JVM) bytecode and interoperates with other Java code and libraries. Most Java code is also syntactically valid Groovy.</p>
                <p>Scala runs on the Java platform (Java Virtual Machine) and is compatible with existing Java programs. It also runs on Android smartphones. An alternative implementation exists for the .NET platform, but it has not been kept up to date.
                  Scala has the same compilation model as Java and C# (separate compilation, dynamic class loading), so Scala code can call Java libraries (or .NET libraries in the .NET implementation).Scala's operational characteristics are the same as Java's. The Scala compiler generates byte code that is nearly identical to that generated by the Java compiler. In fact, Scala code can be decompiled to readable Java code, with the exception of certain constructor operations. To the JVM, Scala code and Java code are indistinguishable.</p>
              </div>
      </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题