简体   繁体   中英

modifying font size with javascript on responsive website

I am making a responsive page with bootstrap. In the middle of the screen i have a text:

<p id="entershop" ><a class=no-deco  href="shop.html">enter shop</a></p>

The page is using bootstrap, so the p is inside a div that has a certain size. I made a script that creates an effect that the p gets bigger and smaller. The p has the size 7rem and it goes from 7 to 10 with this script:

var time = 100;
var up = true;
var size = 7.0;
var getbiggersmaller  = function () {
var text = document.getElementById("entershop");


if (size > 9.5){
    up = false;
}
if (size< 7){
    up = true;
}
if (up){
    size+= 0.1;
    text.style.fontSize = size.toString() +"rem";
   // console.log(size.toString() +"rem");
}

if (up == false){
    size-= 0.1;
    text.style.fontSize = size.toString() +"rem";
   // console.log(size.toString() +"rem");
}


}

window.onload = function() {

setInterval(getbiggersmaller,time);
};

It looks fine on my 16:10 monitor but when I resize the window, the font gets way too big. I need a calculation / script which makes the amount the size is in-/decremented and the original font size etc dependant of the screen size. As i am a beginner, I dont really know where to start :(

I would strongly suggest using media query instead of javascript. But if you are bent on using javascript I would suggest you use the unit 'pixel' instead of 'rem' because pixel stays constant and the value doesn't change. While rem changes according to the website design and it is translated to pixel after that calculation.Which may vary from situation to situation.Also i think you forgot to put quotes around the class name. A Media query is a CSS technique used for creating responsive websites.Using media queries you can manipulate behaviour of your elements on various screen sizes. link to basic media query tutorial For example

html

<p id="entershop" ><a class="no-deco"  href="shop.html">enter shop</a></p>

css:

@media only and screen(min-width:1200px) {
    .a.no-deco {
        font-size:9.5rem;
    }
}
@media only screen and (min-width: 992px) {
    .a.no-deco {
        font-size:8rem;
    }    
}

...and so on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM