简体   繁体   中英

How do I get JavaScript functions in html

I've done Java for a while now and am moving to web development- I am having some troubles however, My code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">

    var getHeight = function() {

        return $(window).height();

    }

</script>

I want to get the height of the window here,

img.pos_fixed {

        position:fixed;
        top:getHeight() / 2;
        right:250px;

    }

but it does not display in the middle of the screen. I am very new so please don't bash on me that I should learn html/javascript/css as I already am.

You're attempting to call javascript functions from css.

Instead you'll have to set the css from within javascript:

var obj= document.createElement('img');
obj.style.top = getHeight() / 2 ;

You could close your jquery script tag,

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>

and use pure css

img.pos_fixed {
    position:fixed;
    top:50%;
    right:250px;
}

Edit

Alternative with JavaScript, you should probably wait for document.ready -

$(document).ready(function() {
  $("img.pos_fixed").css('top','50%'); // same css
});

我会做这样的事情:

$("img.pos_fixed").css({ 'position': 'fixed', 'top': '50%', 'right': '250px' });

You should include the jquery library in a separate script tag like this.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Write your jquery code in another script tag then.

<script type="text/javascript">
    var getHeight = function(){
        return $(window).height();
    }
    var img_height = getHeight/2;
</script>

You can set CSS from script itself.

<script type="text/javascript">
    $("img.pos_fixed").css('top',img_height);
</script>

You can put the rest of the styles in a style tag.

<style>
    img.pos_fixed {
        position:fixed;
        right:250px;
    }
</style>

first of all you can not use javascript function inside css code. but you can change any css of an element using jquery/javascript . if you want to place the image in the middle of the screen from top than you can do that by only css . no need to use javascript .

<img class="middle_img" src="https://www.ourkidssports.com/js/tiny_mce/plugins/imagemanager/football_public_domain.jpg" alt="football">
<style type="text/css">
    .middle_img{
        height:100px;
        width:100px;
        position:fixed;
        top:50%;
        left:50%;
    }
</style>

here is the jsfiddle link: http://jsfiddle.net/banded_krait/Cv3ny/

NB: position:fixed; will fixed the image to the screen. it will not scroll if you scroll your page.

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